首页 > 解决方案 > 在haskell函数的归纳步骤中检查字符串中的空格

问题描述

我正在尝试计算不包括空格的字符串长度。我不能使用长度、过滤器和 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 == " "

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

标签: haskell

解决方案


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

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

countLetters :: String -> Int
countLetters "" = 0
countLetters (' ':xs) = countLetters xs
countLetters str = 1 + countLetters (tail str)

通常,使用模式匹配而不是使用headand会更好tail,因为tail空列表会引发错误,并且通过使用模式匹配,我们知道列表不为空:

countLetters :: String -> Int
countLetters "" = 0
countLetters (x:xs)
    | x == ' ' = countLetters xs
    | otherwise = 1 + countLetters xs

推荐阅读