【发布时间】:2016-04-29 17:18:09
【问题描述】:
首先考虑以下代码,它计算字符串中空格的数量:
countSpaces :: String -> Int
countSpaces [] = 0
countSpaces (c : restOfString)
= d + countSpaces restOfString
where d = if c == ’ ’ then 1
else 0
这是我的问题:
1,如果我拨打电话:countSpaces "abc",那么当此函数尝试将字符串"abc" 与(c: restOfString) 匹配时会发生什么。我的意思是,restOfString 在这次通话中是:"abc",但 (c:restOfString) 是什么?您正在向restOfstring 'consing' 某些东西(变量?c),然后您尝试匹配?我就是不明白。
2,我尝试运行代码,但出现解析错误,为什么?
输入'''解析错误
3,这个函数会调用countSpaces 到无穷大吗?因为restOfString 总是相同的并且没有减少,例如。拨打电话countSpaces "aaa" 在第一次通话、第二次通话或任何通话后都不会改变,对吧?
- 后来添加*
现在考虑完成相同任务的代码:
countSpaces :: String -> Int
countSpaces [] = 0
countSpaces (’ ’ : restOfString)
= 1 + countSpaces restOfString
countSpaces (_ : restOfString)
= 0 + countSpaces restOfString
1,所以如果我们尝试拨打电话countSpaces "abc",则模式(’ ’ : restOfString) 会变得更大,因为每次调用countSpaces 这只会将' ' 转换为restOfString,除非每次@ 987654339@ 将被调用,字符串中的第一个字符将更改为:' '。所以在countSpaces "abc" 的第一次调用中,(’ ’ : restOfString) 是 ' ':"bc",这很令人困惑,因为它用空白代替了 "a",而不是使用它,所以我们得到:" abc"
【问题讨论】:
-
"abc"只是['a', 'b', 'c']或'a':'b':'c':[]的语法糖。 -
你使用了奇怪的撇号。比较一下:
'和你的’。他们是不同的角色。