繁体   English   中英

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

[英]Are variables in list comprehensions immutable?

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

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

例如,在上面的例子中, x似乎改变了它的值。 这是真正发生的事情,还是在这里工作更复杂?

Haskell中没有变量,只有绑定到名称的值。

像这样的列表理解将变成什么实际上是monadic列表代码:

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

然后这进一步减少到使用>>=

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

然后我们可以看一下[]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)`

所以取代return

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

然后>>=

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

现在我们可以减少它:

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成为一个参数一个lambda函数,然后在整个目标列表映射。

暂无
暂无

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

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