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

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

    For your first question, foldr already has a case for the empty list, so you need not and should not provide a case for it in your own map.

    map' f = foldr (\x xs -> f x : xs) []
    

    The same holds for filter'

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

    Nothing is wrong with your lambda expressions, but there is something wrong with your definitions of filter' and map'. In the cons case (x:xs) you eat the head (x) away and then pass the tail to foldr. The foldr function can never see the first element you already ate. :)

    Alse note that:

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

    is equivalent (η-equivalent) to:

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

提交回复
热议问题