在haskell函数的归纳步骤中检查字符串中的空格

在haskell函数的归纳步骤中检查字符串中的空格,haskell,Haskell,我试图计算字符串的长度,不包括空格。 我不能使用长度、过滤器和if-else。只有递归。 我目前的代码是: countLetters :: String -> Int countLetters "" = 0 countLetters str = 1+ countLetters(tail str) 我想做的事 countLetters :: String -> Int countLetters "" = 0 countLetters (&quo

我试图计算字符串的长度,不包括空格。 我不能使用长度、过滤器和if-else。只有递归。 我目前的代码是:

countLetters :: String -> Int
countLetters "" = 0
countLetters str = 1+ countLetters(tail str)
我想做的事

countLetters :: String -> Int
countLetters "" = 0
countLetters (" ",xs) = 0 + countLetters(xs)
countLetters str = 1+ countLetters(tail str)
但我得到的是:

Couldn't match type `([Char], String)' with `[Char]'
  Expected type: String
    Actual type: ([Char], String)
In the pattern: (" ", xs)
  In an equation for `countLetters':
      countLetters (" ", xs) = 0 + countLetters (xs)
我还试着去掉额外的归纳步骤并列举条件

fromEnum head str!=" "
所以,如果字符串的开头是空白,那么值应该是1,但是!=不是有效的运算符。 偶数会让步

   head str == " "
<interactive>:22:13: error:
    * Couldn't match expected type `Char' with actual type `[Char]'
    * In the second argument of `(==)', namely `" "'
      In the expression: head str == " "
      In an equation for `it': it = head str == " "
headstr==“”
:22:13:错误:
*无法将预期类型“Char”与实际类型“[Char]”匹配
*在“(==)”的第二个参数中,即““””
在表达式中:head str==“”
在“it”的方程式中:it=head str==“”

所以请帮我找到另一种方法。

您在这里犯了两个错误。首先,列表的“cons”使用
(:)
作为数据构造函数,因此您使用的是
(“”:xs)
,而不是
(“”,xs)

此外,
String
Char
s的列表,这意味着元素是
Char
s,而不是
String
s,因此您应该使用
'
,而不是
'


您的第二个代码片段非常接近,您刚刚搞错了模式。带有头
x
和尾
xs
的列表被写入
(x:xs)
,而不是
(x,xs)
。(另外,
对头部不起作用,因为它是一个字符串而不是字符-希望你能自己解决这个问题。)@RobinZigmond我写了
countlets(x:xs)=如果x==,那么0+countlets(xs)或者1+countlets(xs)
这是可行的,但如果没有if-else,我仍然不明白如何做到这一点。
countLetters :: String -> Int
countLetters "" = 0
countLetters (' ':xs) = countLetters xs
countLetters str = 1 + countLetters (tail str)
countLetters :: String -> Int
countLetters "" = 0
countLetters (x:xs)
    | x == ' ' = countLetters xs
    | otherwise = 1 + countLetters xs