Examples of Haskell Applicative Transformers

后端 未结 4 552
别跟我提以往
别跟我提以往 2021-02-08 06:41

The wiki on www.haskell.org tells us the following about Applicative Transformers:

So where are applicative transformers? The answer is, that we do not ne

4条回答
  •  你的背包
    2021-02-08 07:13

    The wiki article says that liftA2 (<*>) can be used to compose applicative functors. It's easy to see how to use it from its type:

    o :: (Applicative f, Applicative f1) =>
         f (f1 (a -> b)) -> f (f1 a) -> f (f1 b)
    o = liftA2 (<*>)
    

    So to if f is Maybe and f1 is [] we get:

    > Just [(+1),(+6)] `o` Just [1, 6] 
    Just [2,7,7,12]
    

    The other way around is:

    >  [Just (+1),Just (+6)] `o` [Just 1, Just 6]
    [Just 2,Just 7,Just 7,Just 12]
    

    As @McCann said your ex function is equivalent to liftA2 (:):

    test1 = liftA2 (:) "abc" ["pqr", "xyz"]
    

    To use (:) with deeper applicative stack you need multiple applications of liftA2:

    *Main> (liftA2 . liftA2) (:) (Just "abc") (Just ["pqr", "xyz"])
    Just ["apqr","axyz","bpqr","bxyz","cpqr","cxyz"]
    

    However it only works when both operands are equally deep. So besides double liftA2 you should use pure to fix the level:

    *Main> (liftA2 . liftA2) (:) (pure "abc") (Just ["pqr", "xyz"])
    Just ["apqr","axyz","bpqr","bxyz","cpqr","cxyz"]
    

提交回复
热议问题