Applying a list of functions in Haskell

后端 未结 3 1067
遥遥无期
遥遥无期 2021-01-13 04:43

I wrote a function that applies a list of functions to an item.

applyAll :: [a -> b] -> a -> [b]
applyAll [] _ = []
applyAll (f:fs) x = (f x) : (a         


        
3条回答
  •  暖寄归人
    2021-01-13 05:18

    Lee's solution is what I'd recommend, but this reads perhaps even nicer:

    import Control.Applicative
    
    applyAll' fs v = fs <*> pure v
    

    or

    applyAll'' fs v = fs <*> [v]
    

    This sort of makes stuff more complicated than necessary, though: we really only need the Functor instance of lists, whereas applyAll' injects and immediately extracts from the Applicative instance.

提交回复
热议问题