4 ms·
Can you explain the imperative code? I understand that it has to do with lists being monads and all, but I don't get why (return ([1..10]*2)) :: [Integer]
by icandoitbetter 16y ago
Can you explain the imperative code? I understand that it has to do with lists being monads and all, but I don't get why
(return ([1..10]*2)) :: [Integer]
doesn't work. What's the magic behind
x <- [1..10]
?
- tkahn6 16y agoThat `do` expressions is equivalent to [1..10] >>= (\x -> return (x * 2)) and the definition of (>>=) for a List monad is instance Monad [] where return a = [a] xs >>= f = concat (map f xs) `xs` becomes bound to [1..10] `f` becomes bound to (\x -> return (x * 2)) we we map `f` over each element in the list and get mini-lists. `x` gets bound to each element in the list, x is multiplied by 2, and then returned into a list (1 becomes [2], 2 becomes [4], and so on). So we get: concat [[2],[4],[6]..[20]] And then we concatenate the mini-lists together to get. [2,4..20] As an aside, this is also equivalent [1..10] >>= return . (* 2)
- icandoitbetter 16y agoThanks!