haskell - 在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 == " "
所以请帮我找到另一种方法。
解决方案
你在这里犯了两个错误。首先,列表的“缺点”(:)
用作数据构造函数,因此您使用的是(" ":xs)
,而不是(" ",xs)
。
此外,aString
是 s 的列表,Char
因此这意味着元素是Char
s,而不是String
s,因此您应该使用' '
,而不是:" "
countLetters :: String -> Int
countLetters "" = 0
countLetters (' ':xs) = countLetters xs
countLetters str = 1 + countLetters (tail str)
通常,使用模式匹配而不是使用head
and会更好tail
,因为tail
空列表会引发错误,并且通过使用模式匹配,我们知道列表不为空:
countLetters :: String -> Int
countLetters "" = 0
countLetters (x:xs)
| x == ' ' = countLetters xs
| otherwise = 1 + countLetters xs
推荐阅读
- javascript - 如何在 Nestjs 中全局启用 Multer(fileUpload) 包?
- android - 相关的导致错误的小部件是 Scaffold
- html - 即使一切正确,我的背景图像也不会加载
- qt - QML TabView 创建顺序
- java - Spring预定的工作没有被实例化
- assembly - 从一个文件读取并写入另一个文件 - MIPS
- html - 如何使用 ons-navigator (Onsen UI) 检查当前页面
- dataframe - Shinyapp io 服务器上的应用程序不会在表格中显示最新日期,但在本地计算机上它可以工作
- javascript - 无法传递参数反应原生 5.x
- javascript - 有什么办法可以让代码更短