使用isUpper功能时遇到问题

时间:2014-10-23 19:25:02

标签: haskell

以这种方式编写otherwise部分是否可以?该函数应该降低大写字母并将空格放在前面。它一直给出错误。

functionl s
    | s==[]      = error "empty"
    | otherwise  = [ if isUpper c then (" " ++ toLower c) else c | c <-read s::[Char] ]

2 个答案:

答案 0 :(得分:4)

首先,请注意,(" "++ toLower c)的返回类型是字符串([Char]),如果它已正确完成 - 但事实并非如此。我会在下面告诉你。 但在此之前,请注意,在此特定列表理解中,您有else c这是一个Char

您的退货类型必须匹配。

这可能是一个合适的替代品:concat [ if (isUpper c) then (" "++[c]) else [c] | c <-s ]

答案 1 :(得分:4)

你的列表理解几乎正如@Arnon所示,但你绝对可以使用递归更容易地实现这个功能:

-- A descriptive name and a type signature help
-- tell other programmers what this function does
camelCaseToWords :: String -> String
camelCaseToWords [] = []
camelCaseToWords (c:cs)
    | isUpper c = ' ' : toLower c : camelCaseToWords cs
    | otherwise = c : camelCaseToWords cs

现在,这个模式可以被抽象为使用fold,这是Haskell相当于一个基本的for循环:

camelCaseToWords cs = foldr replacer [] cs
    where
        replacer c xs
            | isUpper c = ' ' : toLower c : xs
            | otherwise = c : xs

这里迭代的每一步都由replacer执行,它取当前字符c,累加值xs并返回一个新值,以便在下一次迭代中使用。折叠的初始值为[],然后在整个字符串上执行。