首页 > 解决方案 > Haskell:无法将类型“Char”与“[Char]”匹配预期类型:[String] 实际类型:String

问题描述

我有这个代码:

censName :: String -> String
censName [] = []
censName xs = unwords(censWords(words xs))

censWords :: [String] -> [String]
censWords [] = []
censWords (x:xs) = if isUpper(head x) then replace(tail x) else censWords xs 

replace :: String -> String
replace [] = []
replace (x:xs) = '*':replace xs

错误说:

Couldn't match type ‘Char’ with ‘[Char]’
  Expected type: [String]
    Actual type: String

我的问题是:为什么!?我的意思是,在 replace(tail x) x 中,x 是一个字符串,那么为什么它需要 [String]?

在此处发布的类似问题上,我找不到任何适合我的问题。

标签: haskell

解决方案


censWords :: [String] -> [String]
                      -- ^^^^^^^^ expected
censWords (x:xs) = if .. then replace(tail x) else ..
                           -- ^^^^^^^^^^^^^^^ actual value

返回值是单个字符串,但需要一个字符串列表。

问题不在于对 的调用replace,而在于它返回的值类型错误,而不是预期的值。


推荐阅读