我有一个字符串列表(见下文),如何将这些字符串连接成一个包含一个字符串的列表。
我有一个字符串列表(见下文),如何将这些字符串连接成一个包含一个字符串的列表。
["hello","stack","overflow"]
转换成
["hellostackoverflow"]
我只能导入Data.Char和Data.List这两个模块。
我有一个字符串列表(见下文),如何将这些字符串连接成一个包含一个字符串的列表。
["hello","stack","overflow"]
转换成
["hellostackoverflow"]
我只能导入Data.Char和Data.List这两个模块。
将列表中的每个字符串视为字符列表
["hello","stack","overflow"] :: [[Char]]
连接是将多个列表连接成一个的过程。其必须有以下类型:
concat :: [[a]] -> [a]
如果你有这样一个功能,那么你已经完成了一半的工作。你正在寻找一种方法来获得
["hellostackoverflow"]
由于连接的结果。再次查看它的类型:
["hellostackoverflow"] :: [[Char]]
这是与您一开始所拥有的类型相同,只不过列表中只有一个元素。现在,您需要一个能将东西放入列表中的函数,它必须拥有一个类型。
putToList :: a -> [a]
一旦你有了 concat
和 putToList
函数,你的解决方案就几乎完成了。最后需要做的事情就是像这样组合它:
Once you'll have both concat
and putToList
functions, your solution will be almost ready. Last thing you need to do is to compose it like that:
myConcatenation = putToList . concat
我建议您使用Hoogle按类型搜索现有函数。
concat ["hello","stack","overflow"] -- => "hellostackoverflow"
您也可以使用列表单子来将列表缩减为单个字符串,然后重新将结果包装在一个列表中。
> [["hello", "stack", "overflow"] >>= id]
["hellostackoverflow"]
上述代码避免了显式使用Control.Monad.join
:
> import Control.Monad
> [join ["hello", "stack", "overflow"]
["hellostackoverflow"]
xs >>= id
和 join xs
等同于 concat xs
。为什么要不必要地使一个简单的操作变得复杂呢? - Kwarrtz[]
的单子属性来实现目标,而不是让它变得更加复杂。 - user2556165
concat
- 如果你想要它作为一个列表,使用return . concat
(如果你在 GHCi 中尝试的话,不要忘记类型注释:return . concat $ ["hello","stack","overflow"] :: [String]
) - Random Dev