简体   繁体   English

Haskell函数,将单词列表转换为字符串

[英]a Haskell function that converts a list of words to a string

For example: 例如:

wordsToString ["all","for","one","and","one","for","all"]
"all for one and one for all"

My code works without a type declaration: 我的代码无需类型声明即可工作:

wordsToString [] = ""
wordsToString [word] = word
wordsToString (word:words) = word ++ ' ':(wordsToString words)

But when I do the type check,it shows that it is a list of Chars which seems wrong to me as I'm supposed to declare the input as a list of strings and get a string as the output: 但是当我进行类型检查时,它表明这是一个Chars列表,这对我来说似乎是错误的,因为我应该将输入声明为字符串列表并获取字符串作为输出:

*Main> :type wordsToString
wordsToString :: [[Char]] -> [Char]

I want to change the declaration to wordsToString::[(String)]->[String] but it won't work 我想将声明更改为wordsToString::[(String)]->[String]但它不起作用

I want to change the declaration to wordsToString::[(String)]->[String] but it won't work 我想将声明更改为wordsToString::[(String)]->[String]但它不起作用

No, you want to change the declaration to wordsToString :: [String] -> String . 不,您想将声明更改为wordsToString :: [String] -> String You aren't getting a list of strings out, just a single one. 您不会得到一个字符串列表,只有一个。

The function is called concat : 该函数称为concat

concat :: Foldable t => t [a] -> [a]
concat xs = foldr (++) [] xs

In your case, you want to insert a whitespace between the characters. 对于您的情况,您想在字符之间插入一个空格。 This function is called intercalate : 此函数称为intercalate

intercalate :: [a] -> [[a]] -> [a]

It's defined in terms of intersperse . 它是根据intersperse定义的。

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

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