What is “lifting” in Haskell?

后端 未结 5 708
南方客
南方客 2020-12-22 16:07

I don\'t understand what \"lifting\" is. Should I first understand monads before understanding what a \"lift\" is? (I\'m completely ignorant about monads, too :) Or can some

5条回答
  •  暖寄归人
    2020-12-22 16:12

    Let's start with an example (some white space is added for clearer presentation):

    > import Control.Applicative
    > replicate 3 'a'
    "aaa"
    > :t replicate
    replicate        ::         Int -> b -> [b]
    > :t liftA2
    liftA2 :: (Applicative f) => (a -> b -> c) -> (f a -> f b -> f c)
    > :t liftA2 replicate
    liftA2 replicate :: (Applicative f) =>       f Int -> f b -> f [b]
    > (liftA2 replicate) [1,2,3] ['a','b','c']
    ["a","b","c","aa","bb","cc","aaa","bbb","ccc"]
    > ['a','b','c']
    "abc"
    

    liftA2 transforms a function of plain types to a function of same types wrapped in an Applicative, such as lists, IO, etc.

    Another common lift is lift from Control.Monad.Trans. It transforms a monadic action of one monad to an action of a transformed monad.

    In general, "lift" lifts a function/action into a "wrapped" type (so the original function gets to work "under the wraps").

    The best way to understand this, and monads etc., and to understand why they are useful, is probably to code and use it. If there's anything you coded previously that you suspect can benefit from this (i.e. this will make that code shorter, etc.), just try it out and you'll easily grasp the concept.

提交回复
热议问题