Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

try to define filter function myself in Haskell and failed

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading