Haskell 空列表生成器
Haskell如何处理列表生成器?具体来说,为什么会这样Haskell 空列表生成器,haskell,Haskell,Haskell如何处理列表生成器?具体来说,为什么会这样 f n = [x:xs | x <- [1..n], xs <- []] 缩小后的答案是 [x:xs | x <- [1..n], xs <- []] …相当于 do x <- [1..n] xs <- [] return (x:xs) …也就是说(在用列表monad替换(>>=)和return的定义之后): 空列表上的concatMap(顾名思义,它只是map,后跟con
f n = [x:xs | x <- [1..n], xs <- []]
缩小后的答案是
[x:xs | x <- [1..n], xs <- []]
…相当于
do
x <- [1..n]
xs <- []
return (x:xs)
…也就是说(在用列表monad替换(>>=)
和return
的定义之后):
空列表上的concatMap
(顾名思义,它只是map
,后跟concat
)给出了一个空列表,因此它变成了
concatMap (\x -> []) [1..n]
…这相当于将
[1..n]
的每个元素替换为一个空列表,然后concat
-ing生成一个空列表的结果。对于x:xs
中的xs
在每个“迭代”中是什么,没有答案,因为x:xs
没有“迭代”。思考一下这个表达式:[undefined | |@duplode给出了一个关于它为什么不起作用的很好的答案。但是我假设,您想创建一个列表,每个列表都包含一个元素;您可以使用创建单个元素列表的fn=[x:xs | x来创建,但是为什么要这样做呢?只是fn=[x]|x
[1..n] >>= \x ->
[] >>= \xs ->
return (x:xs)
-- Or, without the line breaks:
[1..n] >>= \x -> [] >>= \xs -> return (x:xs)
concatMap (\x -> concatMap (\xs -> [x:xs]) []) [1..n]
concatMap (\x -> []) [1..n]