The composition of functions in a list of functions!

后端 未结 5 2029
灰色年华
灰色年华 2020-12-31 20:47

I need to define a function \'Compose\' which takes a list \'L\' which is a list of functions. When I specify a parameter that will suit all the functions in the list, the l

5条回答
  •  爱一瞬间的悲伤
    2020-12-31 21:19

    If the solution is a one-line answer, it could be something involving a fold:

    compose :: [a -> a] -> a -> a
    compose fs v = foldl (flip (.)) id fs $ v
    

    http://haskell.org/haskellwiki/Compose

    You can also implement it as a right fold, which works the way you want:

    compose = foldr (.) id
    
    *Main> let compose = foldr (.) id
    *Main> compose [\x -> x+1, \x -> 2 * x, id] 3
    7
    

提交回复
热议问题