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

后端 未结 8 2505
一个人的身影
一个人的身影 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:46

    I would define map using foldr and function composition as follows:

    map :: (a -> b) -> [a] -> [b]
    map f = foldr ((:).f) []
    

    And for the case of filter:

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

    Note that it is not necessary to pass the list itself when defining functions over lists using foldr or foldl. The problem with your solution is that you drop the head of the list and then apply the map over the list and this is why the head of the list is missing when the result is shown.

提交回复
热议问题