我正在通过这本书The Haskell Road to Logic, Maths and Programming . (到目前为止,我还是希望继续这样做 . )我已经了解了函数,类型声明,保护方程,关于列表模式匹配以及where和let的一些知识 .
我坚持练习1.17,它要求我们写一个函数substring :: String - > String - > Bool其中:
-
如果xs是ys的前缀,则xs是ys的子串
-
如果ys等于y:ys ' and xs is a substring of ys',xs是ys的子串
-
没有别的东西是ys的子串
我使用了前面例子中提供的前缀函数:
prefix :: String -> String -> Bool
prefix [] ys = True
prefix (x:xs) [] = False
prefix (x:xs) (y:ys) = (x==y) && prefix xs ys
然后尝试:
substring :: String -> String -> Bool
subsstring xs [] = False
substring xs (y:ys) | prefix xs (y:ys) = True
| substring xs ys = True
| otherwise = False
......以及其他可能的排列 .
当我运行 substring "abc" "xxxabcyyy"
时,我得到 True
,但是当我运行 substring "abc" "xxxabyyy"
时,我得到“*异常:substring.hs:(3,0) - (5,45):函数substring ". I can't figure out why. I don't understand how there could be non-exhaustive patterns when I use "中的非详尽模式” .
顺便说一下,这本书还没有涵盖if-then-else . 我现在更愿意将其从我的解决方案中删除 .
1 回答
你在函数名中有一个拼写错误:
由于拼写错误,这声明了一个新函数
subsstring
,而不是substring
函数的情况 .substring
函数本身没有任何与[]
的第二个参数匹配的情况 .