haskell - 使用“否则”时如何获得“非详尽模式”异常
问题描述
我试图证明表格的数字p_1 * ... * p_k + 1
并不都是素数,为此,我编写了这段代码
sieve :: [Integer] -> [Integer]
sieve (0:xs) = sieve xs
sieve (x:xs) = x : sieve (mark x xs)
where
mark :: Integer -> [Integer] -> [Integer]
mark n (y:ys)
| rem y n == 0 = 0 : (mark n ys)
| otherwise = y : (mark n ys)
checkPrime' :: Integer -> Bool
checkPrime' n = elem n (sieve [n])
listPrimeFromTo' :: Integer -> Integer -> [Integer]
listPrimeFromTo' k n = sieve [k..n]
checkEulerPrimes = forall [(product xs) + 1| n <- [2..], let xs = listPrimeFromTo' 2 n] checkPrime'
我得到这个例外:
*** 例外:Ch3.hs:(11,2)-(13,31):功能标记中的非详尽模式
但是,在函数的定义中mark
,我使用otherwise
了 ,所以怎么可能存在函数的定义没有为此指定任何规则的情况。我的意思是我认为使用关键字otherwise
可以确保没有未用尽的模式。
解决方案
otherwise
确实是一个总能成功的守卫;但仅当相关模式已经匹配时才考虑守卫。所以,在
foo (x:xs) | otherwise = bar
我们只会在参数匹配模式bar
时看到结果。与is类似的模式,它总是匹配并且不绑定任何新变量,所以:foo
x:xs
otherwise
_
foo (x:xs) | otherwise = bar
foo _ = baz
永远不会抛出不匹配的模式异常。
推荐阅读
- javascript - Angular中多个HTTP请求的最佳方式
- c - 搜索到链表
- javascript - 未捕获的类型错误:如何修复 jQuery 冲突?
- sql - 在一行中显示一对多关系
- powershell - 复制文件夹时出错!使用“0”参数调用“ExecuteQuery”的异常:“远程服务器返回错误:(400) 错误请求。”
- wpf - TabItem 样式触发器不会在应用程序启动时更新
- .net - 如何从 .net 客户端为 ibm amqp 主题创建不可修改的持久订阅者?
- c++ - 在 cmake 中需要具有依赖项的共享库
- haskell - Haskell Stack - 如何在堆栈测试期间禁用复制可执行文件?
- git - 无法让 git-receive-pack 与 golang ssh 隧道一起工作