在 Haskell 中展平列表和单个元素的混合
Flattening a mixture of lists and single elements in Haskell
在 F# 中,我可以使用 yield
/yield!
语法将单个元素和数组的混合物连接到单个集合中,例如
let result = seq {
yield 1
yield! [2;3;4;5]
yield! [6;7]
yield 8
}
printfn "%A" result
// Prints: seq [1; 2; 3; 4; ...]
我想知道 Haskell 中是否有类似的方法。
等同于:
result = concat [
[1],
[2,3,4,5],
[6,7],
[8]
]
您的评论:
It would work, but I'd need to turn my single elements into lists first.
有点没抓住重点。您的 F# 版本已经 将单个元素转换为列表。这就是 yield
所做的。
但是,如果您真的对语法不感兴趣,您可以与作者 monad 非常接近地复制它:
import Control.Monad.Writer
yield x = tell [x]
yield' = tell
result = execWriter do
yield 1
yield' [2,3,4,5]
yield' [6,7]
yield 8
在 F# 中,我可以使用 yield
/yield!
语法将单个元素和数组的混合物连接到单个集合中,例如
let result = seq {
yield 1
yield! [2;3;4;5]
yield! [6;7]
yield 8
}
printfn "%A" result
// Prints: seq [1; 2; 3; 4; ...]
我想知道 Haskell 中是否有类似的方法。
等同于:
result = concat [
[1],
[2,3,4,5],
[6,7],
[8]
]
您的评论:
It would work, but I'd need to turn my single elements into lists first.
有点没抓住重点。您的 F# 版本已经 将单个元素转换为列表。这就是 yield
所做的。
但是,如果您真的对语法不感兴趣,您可以与作者 monad 非常接近地复制它:
import Control.Monad.Writer
yield x = tell [x]
yield' = tell
result = execWriter do
yield 1
yield' [2,3,4,5]
yield' [6,7]
yield 8