为什么我会得到“功能非穷举模式...”。当我调用我的Haskell子字符串函数? [英] Why am I getting "Non-exhaustive patterns in function..." when I invoke my Haskell substring function?
问题描述
一>。 (我只是通过第一章的中途,但我很享受它,并打算继续。)我已阅读了第1.5节玩Haskell游戏,其中包含许多其他示例让你熟悉[Haskell]。到目前为止,我已经了解了函数,类型声明,守护方程,关于列表模式匹配的一些信息,以及在哪里&
我坚持练习1.17,它要求我们编写一个函数substring :: String - > String - > Bool其中:
- 如果xs是ys的前缀,则xs是ys的子字符串 如果ys等于y:ys'和xs,则
- 是ys'的子字符串,xs是ys的子字符串
- 其他都不是ys的子字符串
我使用前面示例中提供的前缀函数:
prefix :: String - >字符串 - > Bool
prefix [] ys = True
前缀(x:xs)[] = False
前缀(x:xs)(y:ys)=(x == y)&& amp ;前缀xs ys
然后尝试:
substring :: String - >字符串 - > Bool
subsstring xs [] = False
substring xs(y:ys)|前缀xs(y:ys)= True
| substring xs ys = True
|否则= False
...并且可能会对此进行其他排列。
当我运行 substringabcxxxabcyyy
时,我得到 True
,但是当我运行 substringabcxxxabyyy
我得到 * 异常:substring.hs:(3,0) - (5,45):函数子串中的非穷举模式。我无法弄清楚为什么。我不明白当我使用其他时,如何有非穷举的模式。
顺便说一句,这本书还没有涵盖if-then-else。
在函数名称中有一个拼写错误:
subsstring xs [] = False
由于错字,它声明了一个新函数 subsstring
,而不是子字符串
函数。
[]
。
I'm working my way through the book The Haskell Road to Logic, Maths and Programming. (I'm only mid-way through chapter 1, but I'm enjoying it so far and intend to continue.) I've read through the section 1.5 "Playing the Haskell Game" which "consists of a number of further examples to get you acquainted with [Haskell]". So far I've learned about functions, type declarations, guarded equations, a little about list pattern matching, and where & let.
I'm stuck on exercise 1.17, which asks us to write a function substring :: String -> String -> Bool where:
- if xs is a prefix of ys, xs is a substring of ys
- if ys equals y:ys' and xs is a substring of ys', xs is a substring of ys
- nothing else is a substring of ys
I used the prefix function provided in a previous example:
prefix :: String -> String -> Bool
prefix [] ys = True
prefix (x:xs) [] = False
prefix (x:xs) (y:ys) = (x==y) && prefix xs ys
And then tried:
substring :: String -> String -> Bool
subsstring xs [] = False
substring xs (y:ys) | prefix xs (y:ys) = True
| substring xs ys = True
| otherwise = False
...and may other permutations of this.
When I run substring "abc" "xxxabcyyy"
I get True
, but when I run substring "abc" "xxxabyyy"
I get "* Exception: substring.hs:(3,0)-(5,45): Non-exhaustive patterns in function substring". I can't figure out why. I don't understand how there could be non-exhaustive patterns when I use "otherwise".
BTW, the book has not yet covered if-then-else. I'd prefer to keep that out of my solution, for now.
You have a typo in the function name:
subsstring xs [] = False
Because of the typo this declares a new function subsstring
, not a case of the substring
function.
The substring
function itself then doesn't have any case that would match a second parameter of []
.
这篇关于为什么我会得到“功能非穷举模式...”。当我调用我的Haskell子字符串函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!