繁体   English   中英

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

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

例如:

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

我的代码无需类型声明即可工作:

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

但是当我进行类型检查时,它表明这是一个Chars列表,这对我来说似乎是错误的,因为我应该将输入声明为字符串列表并获取字符串作为输出:

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

我想将声明更改为wordsToString::[(String)]->[String]但它不起作用

我想将声明更改为wordsToString::[(String)]->[String]但它不起作用

不,您想将声明更改为wordsToString :: [String] -> String 您不会得到一个字符串列表,只有一个。

该函数称为concat

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

对于您的情况,您想在字符之间插入一个空格。 此函数称为intercalate

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

它是根据intersperse定义的。

暂无
暂无

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

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