简体   繁体   English

将字符串列表连接到一个字符串haskell

[英]Concatenate a list of strings to one string haskell

I have a list of strings (see below) how do I concatenate these strings into one list containing one string. 我有一个字符串列表(请参阅下文),如何将这些字符串连接到一个包含一个字符串的列表中。

["hello","stack","overflow"] 

to

["hellostackoverflow"]

I am just allowed to import Data.Char and Data.List 我只被允许导入Data.Char和Data.List

Consider each string in a list as a list of characters 将列表中的每个字符串视为字符列表

["hello","stack","overflow"] :: [[Char]]

Concatenation is a process of connecting several lists into one. 串联是将多个列表连接成一个列表的过程。 It must have a following type: 它必须具有以下类型:

concat :: [[a]] -> [a]

If you will have such a function, you'll get a half of job done. 如果您拥有这样的功能,那么您将完成一半的工作。 You are looking for a way to get 您正在寻找一种获取途径

["hellostackoverflow"]

as a result of concatenation. 作为串联的结果。 Once again, look at it's type: 再次查看它的类型:

["hellostackoverflow"] :: [[Char]]

It is the same type as you had at the beginning except that there is only one element in a list. 它与开始时的类型相同,只是列表中只有一个元素。 So now you need a function which puts something into a list. 因此,现在您需要一个将内容放入列表的函数。 It must have a type 它必须有一个类型

putToList :: a -> [a]

Once you'll have both concat and putToList functions, your solution will be almost ready. 一旦拥有concatputToList函数,您的解决方案就差不多准备好了。 Last thing you need to do is to compose it like that: 您需要做的最后一件事就是这样编写:

myConcatenation = putToList . concat

I suggest you to use Hoogle to search existing function by it's type. 我建议您使用Hoogle按类型搜索现有功能。

You can also use the list monad to reduce the list to a single string, then re-wrap the result in a list. 您也可以使用list monad将列表简化为单个字符串,然后将结果重新包装在列表中。

> [["hello", "stack", "overflow"] >>= id]
["hellostackoverflow"]

The preceding avoids explicitly use of Control.Monad.join : 前面避免了显式使用Control.Monad.join

> import Control.Monad
> [join ["hello", "stack", "overflow"]
["hellostackoverflow"]

concat ["hello","stack","overflow"] concat [“ hello”,“ stack”,“ overflow”]

"hellostackoverflow" “ hellostackoverflow”

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

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