haskell - 'concat' : transforming a flattened list into a nested list 的逆

标签 haskell

给定 Haskell 中的扁平列表:

['a', 'b','c','d']

如何将其更改为:

[['a'], ['b'], ['c'], ['d']]

最佳答案

描述您想要执行的操作的一种方法是获取列表中的每个元素,并将其与另一个列表单独包装。或者,您希望对列表中的每个元素执行操作 'a' ---> ['a']

每当您谈论将“列表中的每个元素单独转换为其他元素”时,您都在谈论 map [0],因此我们将稍微编写一下此函数喜欢

example :: [Char] -> [[Char]]
example cs = map _ cs

其中 _ 是函数 'a' ---> ['a']。不过,这个函数可以写成显式匿名函数

example :: [Char] -> [[Char]]
example cs = map (\c -> [c]) cs

这将实现我们所需要的!

但是我们可以更进一步。首先,在 Haskell 中,如果应用的最后一个参数与最后一个输入参数相同,则允许您删除。或者,更具体地说,我们也可以将 example 写为

example :: [Char] -> [[Char]]
example = map (\c -> [c])

只需删除参数列表中的 cs 以及作为 map 的参数即可。其次,我们可以注意到 example 的类型比它应有的要弱。当然是更好的编写方式

example :: [a] -> [[a]]
example = map (\c -> [c])

这反射(reflect)出我们没有在内部使用任何特定于 Char 的内容。

[0] 或者,更一般地说,fmap

关于haskell - 'concat' : transforming a flattened list into a nested list 的逆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26772517/

相关文章:

mysql - 如何使用 Snap 的 MysqlSimple snaplet 连接到 MySQL

haskell - vim haskell 模式的视频或教程

Scala 在 Haskell 中的样式 val

haskell - 对于字典序 Ord 实例来说,优雅的习惯用法是什么?

haskell - 构造具有多个字段的 Haskell 数据类型

haskell - 数组索引触发元素的重复评估?

haskell - `to` 镜头进入 zipper

haskell - 证明在 Coq 提取中的作用

twitter-bootstrap - Haskell 等式约束

haskell - Haskell 中的 C 风格枚举?