How would you define map and filter using foldr in Haskell?

后端 未结 8 2507
一个人的身影
一个人的身影 2020-12-05 14:58

I\'m doing a bit of self study on functional languages (currently using Haskell). I came across a Haskell based assignment which requires defining map and filter in terms of

8条回答
  •  感动是毒
    2020-12-05 15:32

    Your solution almost works .) The problem is that you've got two differend bindings for x in both your functions (Inside the patternmatching and inside your lambda expression), therefore you loose track of the first Element.

    map'            :: (a -> b) -> [a] -> [b]
    map' f []       = []
    map' f (x:xs)   = foldr (\x xs -> (f x):xs) [] (x:xs)
    
    filter'             :: (a -> Bool) -> [a] -> [a]
    filter' p []        = []
    filter' p (x:xs)    = foldr (\x xs -> if p x then x:xs else xs ) [] (x:xs)
    

    This should to the trick :). Also: you can write your functions pointfree style easily.

提交回复
热议问题