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

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

    *Main> :{
    *Main| map' :: (a -> b) -> [a] -> [b]
    *Main| map' = \f -> \ys -> (foldr (\x -> \acc -> f x:acc) [] ys)
    *Main| :}
    *Main> map' (^2) [1..10]
    [1,4,9,16,25,36,49,64,81,100]
    
    *Main> :{
    *Main| filter' :: (a -> Bool) -> [a] -> [a]
    *Main| filter' = \p -> \ys -> (foldr (\x -> \acc -> if p x then x:acc else acc) [] ys)
    *Main| :}
    *Main> filter' (>10) [1..100]
    

    In the above snippets acc refers to accumulator and x refers to the last element.

提交回复
热议问题