Haskell: variable scope in list monad -


i reading online haskell book list monad. in book, list monad defined this:

instance monad []       return x = [x]       xs >>= f = concat (map f xs)       fail _ = [] 

and there example of list monad usage this:

prelude> [1,2] >>= \n -> ['a','b'] >>= \ch -> return (n,ch)   [(1,'a'),(1,'b'),(2,'a'),(2,'b')] 

i'm new haskell , question example is, how come variable 'n' available inside lambda expression of return (n,ch). n defined in other lambda expression , don't understand why variable defined in 1 lambda expression available in subsequent lambda expressions. tried converting example below according list monad definition:

prelude> concat (map (\ch -> return (n, ch)) (concat (map (\n -> ['a', 'b']) [1, 2])))  <interactive>:32:29: error: variable not in scope: n 

but can see, got error saying variable n not available in scope of other lambda expression. maybe book presented simplified version of list monad definition?

[1,2] >>= \n -> ['a','b'] >>= \ch -> return (n,ch)   

is not parsed as

[1,2] >>= (\n -> ['a','b']) >>= (\ch -> return (n,ch)) 

but

[1,2] >>= \n -> (['a','b'] >>= (\ch -> return (n,ch))) 

your translation concat / map reflects "wrong" parsing. can adapt correct one.

the first >>= becomes

concat (map (\n -> ???) [1,2]) 

and can translate inner >>= replacing ??? needed:

??? = concat (map (\ch -> ???2) ['a','b']) ???2= return (n,ch) 

result:

concat (map (\n -> concat (map (\ch -> return (n,ch)) ['a','b'])) [1,2]) 

Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -