Alex Rivera | Logout

What is "lifting" in Haskell?

Asked 2010-03-07T08:58:08.727
158

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 someone explain it to me with simple words?

Edit
Report

1 Answer

26

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.

answered 2010-03-07T09:58:37.537

Your Answer