Try to define the filter function as follows
myFilter :: (a -> Bool) -> [a] -> [a]
myFilter f [] = []
myFilter f (x:xs)
| f x = x : myFilter xs
| otherwise = myFilter xs
I put it into the file named myfilter.hs and loaded to ghci. I got the following error
myfilter.hs:5:26: error:
• Couldn't match expected type: a1 -> Bool
with actual type: [a]
• In the first argument of ‘myFilter’, namely ‘xs’
In the expression: myFilter xs
In an equation for ‘myFilter’:
myFilter f (x : xs)
| f x = x : myFilter xs
| otherwise = myFilter xs
• Relevant bindings include
xs :: [a] (bound at myfilter.hs:3:15)
x :: a (bound at myfilter.hs:3:13)
f :: a -> Bool (bound at myfilter.hs:3:10)
myFilter :: (a -> Bool) -> [a] -> [a] (bound at myfilter.hs:2:1)
|
5 | | otherwise = myFilter xs
| ^^
Failed, no modules loaded.
ghci>
What the error about and how can I fix it
CodePudding user response:
You should call myFilter
with the predicate f
and the rest of the list xs
, so:
myFilter :: (a -> Bool) -> [a] -> [a]
myFilter f [] = []
myFilter f (x:xs)
| f x = x : myFilter f xs -- ← call with f as first parameter
| otherwise = myFilter f xs