一个Haskell函数,用于将单词列表转换为字符串

时间:2017-04-24 15:24:53

标签: string list haskell

例如:

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]但不起作用

2 个答案:

答案 0 :(得分:1)

I want to change the declaration to wordsToString::[(String)]->[String] but it won't work

No, you want to change the declaration to wordsToString :: [String] -> String. You aren't getting a list of strings out, just a single one.

答案 1 :(得分:1)

该函数名为concat

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

在您的情况下,您希望在字符之间插入空格。此函数称为intercalate

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

根据intersperse定义。