Applying a list of functions in Haskell

后端 未结 3 1060
遥遥无期
遥遥无期 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.

    0 讨论(0)
  • 2021-01-13 05:33

    This function actually already exists as a special case of a monadic function:

    applyAll :: [a -> b] -> a -> [b]
    applyAll = sequence
    
    0 讨论(0)
  • 2021-01-13 05:35

    You could use:

     applyAll l v = fmap ($ v) l
    

    fmap lifts a function over the input list (actually any Functor). $ has type (a -> b) -> a -> b so it applies a function to a given value. ($ v) is a section which applies the given function to v.

    0 讨论(0)
提交回复
热议问题