Function application function in Haskell

前端 未结 3 796
说谎
说谎 2020-12-20 18:28

Let\'s say I have a list of functions

functions = [f, g, h]

each one with type a -> a

I also have a list of values

相关标签:
3条回答
  • 2020-12-20 18:55
    zipWith ($) f v
    

    $ is function application. The fact that it has particularly low precedence throws people for a loop sometimes.

    0 讨论(0)
  • 2020-12-20 18:57

    Here's another option which might make you think a bit.

    >>> import Control.Applicative
    >>> let functions = ZipList [(+1), (*2), (*10)]
    >>> let values    = ZipList [1, 2, 3]
    >>> getZipList (functions <*> values)
    [2, 4, 30]
    

    A ZipList is just a wrapper around a list. The definition of <*> for a ZipList says "zip the list of functions (on the left) with the list of arguments (on the right) by applying each function to an argument in turn".

    This is in contrast to the definition of <*> for a regular list, which says "take every possible pair of (function, argument) from these two lists and apply the function to the argument".

    0 讨论(0)
  • 2020-12-20 19:17

    Strangely enough,

    zipWith id functions vals
    

    will work too!

    But, really, zipWith ($) is the right way to write this.

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