Applying multiple functions to the same value point-free style in Haskell

后端 未结 4 642
醉酒成梦
醉酒成梦 2021-02-01 16:14

I was bored one day and wanted to exercise my brain, so I decided to do the 99 Haskell Problems but restricted myself to doing them in point-free style. A problem that seems to

4条回答
  •  一整个雨季
    2021-02-01 16:37

    You will be interested in the Applicative instance of the reader monad:

    instance Applicative (e ->)
    

    Using it you can easily distribute an argument:

    liftA2 (+) sin cos 3
    

    Here sin and cos are functions, which both receive the value 3. The individual results are then combined using (+). You can further combine this with the Category instance of (->), but of cource specialized versions of (.) and id are already defined in the Prelude.

    Background: The Applicative instance for (e ->) really represents the SKI calculus, where (<*>) is the S combinator and pure is the K combinator. S is precisely used to distribute an argument to two functions:

    S f g x = f x (g x)
    

    It takes a function application (f g) and makes both dependent on the value x ((f x) (g x)).

提交回复
热议问题