I have this but I got an error:
-- test if a list contains exactly three characters
test :: [Char] -> Bool
test xs | [_ , _ , _] = True
| otherwise = False
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Pattern matching happens on the left side of the vertical bar. Thus:
As Norman Ramsey rightly notes below, the following code is not a robust alternative solution (because it is very inefficient when applied to (long) finite lists and does not halt on infinite lists) and should thus not be used:
Moreover,
length xs == 0should always be replaced withnull xs.Edit: the question which naturally arises is: how do we generalize this? What if we want to test whether a list has exactly n elements? What if the input may be infinite?
Here’s a solution where the cost is either
nor the length of the list, whichever is smaller—and that’s as efficient a solution, asymptotically, as we can possibly hope for:Usage:
It is unsafe to call this function with a negative length; if the list is infinite, the function won’t terminate, and if the list is finite, it will return
Falsewith cost proportional to the length of the list. An easy fix would be to check in advance (on the first call only) thatnis nonnegative, but this fix would ugly up the code.