J.d*_*doe 0 haskell pattern-matching
首先考虑以下代码,它计算字符串中的空格数:
countSpaces :: String -> Int
countSpaces [] = 0
countSpaces (c : restOfString)
= d + countSpaces restOfString
where d = if c == ’ ’ then 1
else 0
Run Code Online (Sandbox Code Playgroud)
这是我的问题:
1,如果我拨打电话:countSpaces "abc",那么当这个函数试图匹配字符串会发生什么"abc"用(c: restOfString).我的意思restOfString是:"abc"在这次通话中,但是这是(c:restOfString)什么?你正在"勉强"某事(变量?c)restOfstring 然后你想要匹配?我只是不明白.
2,我尝试运行代码但是我得到一个解析错误为什么?
输入'''上的解析错误
3,这个函数会调用countSpaces 无穷大吗?因为restOfString总是相同而不是减少,例如.countSpaces "aaa"第一次通话,第二次或任何通话后拨打电话都不会改变,对吧?
现在考虑完成相同任务的代码:
countSpaces :: String -> Int
countSpaces [] = 0
countSpaces (’ ’ : restOfString)
= 1 + countSpaces restOfString
countSpaces (_ : restOfString)
= 0 + countSpaces restOfString
Run Code Online (Sandbox Code Playgroud)
1,所以如果我们尝试进行调用 countSpaces "abc",模式(’ ’ : restOfString)将变得更大,因为每次countSpaces调用时这只是一个' 'to restOfString,除非每次countSpaces都被调用,字符串中的第一个字符将被更改为:' '.所以在第一次调用countSpaces "abc" 当时(’ ’ : restOfString)是' ':"bc",这是令人困惑的权利,因为它替换"a"为空白而不是消耗它,以便我们得到:" abc"
1,如果我打电话:countSpaces"abc",那么当这个函数试图将字符串"abc"与:(c:restOfString)匹配时会发生什么.
当您使用的利弊操作相匹配的模式:,在左边的元素:是列表中的第一个元素,并在右边:是列表的其余部分.以下是等效的:
"abc" == 'a' : "bc"
Run Code Online (Sandbox Code Playgroud)
由于a String是一个字符列表(具体而言[Char]),因此上述内容也可以写成:
"abc" == 'a' : 'b' : 'c' : []
Run Code Online (Sandbox Code Playgroud)
2,我尝试运行代码但是我得到一个解析错误为什么?
您的解析错误是因为您对单引号使用了错误的字符.您应该使用ASCII/Unicode撇号字符时使用unicode 0x2019 :'
3,这个函数会将countSpaces调用到无穷大吗?
如果你的字符串是无限的,它只会计入无穷大.减少实际发生在这部分:
countSpaces restOfString
Run Code Online (Sandbox Code Playgroud)
要理解原因,请参阅第1部分的答案.在"abc"的情况下,restOfString是"bc".
4,所以如果我们尝试调用countSpaces"abc"的模式:('':restOfString)只会变得更大,因为每次countSpaces被调用时这将只是一个''到restOfString,除非每次countSpaces都会被调用然后字符串中的第一个字符将更改为:''.所以在第一次调用countSpaces"abc"然后('':restOfString)是'':"bc",这是混淆吧?
我认为你的困惑源于模式匹配和构建列表看起来相同的事实.即你写作时会发生什么,(' ':restOfString)完全取决于语境.
您可以将函数定义视为由=符号分隔的两部分:
countSpaces (' ' : restOfString) = 1 + countSpaces restOfString
^ ^ ^ ^ ^
| | | | |
-------------------------------- | ----------------------------
| | |
Pattern Matching Separator Function Body
Run Code Online (Sandbox Code Playgroud)
模式匹配部分不会影响输出.当您(' ' : restOfString)在模式匹配方面使用时,您说,"如果传入countSpaces函数的参数以空格开头,则返回此函数体中的内容.如果第一个字符不是空格,则尝试定义下一个模式".在任何一种情况下(无论是否匹配),传入的值countSpaces都不会以任何方式被修改(它没有在它前面放置空格;这种事情只发生在函数体中).
相反,当你放入(' ' : restOfString)函数体时,你会说"返回restOfString以空格字符为前缀的值".
| 归档时间: |
|
| 查看次数: |
144 次 |
| 最近记录: |