Are list comprehension variables immutable?

Are list comprehension variables immutable?

[x + 1 | x <- [1,2,3,4,5]]

For example, in the above example x, it seems to change its value. Is this what is actually happening, or is something more complicated to work here?

+4
source share
1 answer

Haskell has no variables, only values ​​bound to names.

What a list comprehension, like this, will turn into actually monodic code for a list:

y = [x + 1 | x <- [1, 2, 3, 4, 5]]
y = do
    x <- [1, 2, 3, 4, 5]
    return (x + 1)

Then it further comes down to using >>=:

y = [1, 2, 3, 4, 5] >>= (\x -> return (x + 1))

And then we can look at the definition for the instance Monadfor []:

instance Monad [] where
    return x = [x]
    list >>= f = concat (map f list)
    -- uses the `concatMap` function in the actual definition
    -- where `concatMap f list = concat (map f list)`

So, replacing return:

y = [1, 2, 3, 4, 5] >>= (\x -> [x + 1])

And then >>=:

y = concat (map (\x -> [x + 1]) [1, 2, 3, 4, 5])

Now we can reduce it:

y = concat [[1 + 1], [2 + 1], [3 + 1], [4 + 1], [5 + 1]]
y = concat [[2], [3], [4], [5], [6]]
y = [2, 3, 4, 5, 6]

, , , x - , , x , .

+9

All Articles