Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

liftM vs. raw replicate

Tags:

haskell

ghc

replicate 3 "hi"

produces

["hi", "hi", "hi"]

but

liftM (replicate 3) "hi"

produces

["hhh", "iii"]

How the liftM operates (precisely)?

like image 780
Cartesius00 Avatar asked Dec 09 '25 15:12

Cartesius00


2 Answers

The liftM function is another name for fmap*, which is equivalent to map when it operates on lists.

liftM (replicate 3) "hi"
  = [replicate 3 x | x <- "hi"]
  = [replicate 3 'h', replicate 3 'i']
  = ["hhh", "iii"]

Footnotes

* The difference between liftM and fmap is the different class context, since due to historical reasons, Monad does not imply Functor.

like image 65
Dietrich Epp Avatar answered Dec 12 '25 13:12

Dietrich Epp


Summary: liftM = map.


The liftM function has type Monad m => (a -> b) -> m a -> m b. That is, it takes a function and something in a monad and applies the function "through" the monad. (Or, to look at it another way, it has type Monad m => (a -> b) -> (m a -> m b), i.e. it converts a function into one that operates through a monad.)

In this case we have liftM (replicate 3) ['h','i'] (remember that "hi" is just shorthand for a list of the individual characters), so the monad in question is the list monad. The definition of liftM for lists is equivalent to map (the two functions have the same type, which is a big hint.) Thus:

liftM (replicate 3) ['h','i'] = map (replicate 3) ['h','i']
     = [replicate 3 'h', replicate 3 'i'] = ["hhh","iii"]
like image 45
huon Avatar answered Dec 12 '25 11:12

huon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!