简体   繁体   English

列表推导中的变量是不可变的吗?

[英]Are variables in list comprehensions immutable?

Are variables in list comprehensions immutable? 列表推导中的变量是不可变的吗?

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

For instance, in the above example, x seems to change it's value. 例如,在上面的例子中, x似乎改变了它的值。 Is this what is really happening, or is something more complicated at work here? 这是真正发生的事情,还是在这里工作更复杂?

There are no variables in Haskell, only values bound to names. Haskell中没有变量,只有绑定到名称的值。

What a list comprehension like this will get turned into is actually monadic list code: 像这样的列表理解将变成什么实际上是monadic列表代码:

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

Then this further gets reduced to using >>= : 然后这进一步减少到使用>>=

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

And then we can look at the definition for the Monad instance for [] : 然后我们可以看一下[]Monad实例的定义:

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 : 所以取代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]

So as you can see, it's not that x is a variable that changes values, x becomes the argument to a lambda function that is then mapped across the target list. 因此,大家可以看到,这并不是说x是改变值的变量x成为一个参数一个lambda函数,然后在整个目标列表映射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM