Reputation: 367
Is there a way to look through a list and when you find the values 4 and 5, do something?
I tried foo (4:5:xs) = <do something>
but it doesn't compile
Upvotes: 1
Views: 710
Reputation: 6610
You'll also have to describe what should happen when you don't find 4 and 5!
Let's suppose that you want to return the string "Found"
when you have seen 4 and 5, and "Not found"
otherwise. Then you could use this function:
foo :: [Int] -> String
foo (4:5:xs) = "Found"
foo (_:xs) = foo xs
foo [] = "Not found"
If you don't want to 'do anything' when you do not see 4 and 5, you'll have to change the return type of function to Maybe String
(in this example):
foo :: [Int] -> Maybe String
foo (4:5:xs) = Just "Found"
foo (_:xs) = foo xs
foo [] = Nothing
I would use the second version, so that you don't have to remember what the 'not found' value is.
Upvotes: 5