首页 > 解决方案 > 使用“否则”时如何获得“非详尽模式”异常

问题描述

我试图证明表格的数字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可以确保没有未用尽的模式。

标签: haskellnon-exhaustive-patterns

解决方案


otherwise确实是一个总能成功的守卫;但仅当相关模式已经匹配时才考虑守卫。所以,在

foo (x:xs) | otherwise = bar

我们只会在参数匹配模式bar时看到结果。与is类似的模式,它总是匹配并且不绑定任何新变量,所以:foox:xsotherwise_

foo (x:xs) | otherwise = bar
foo _ = baz

永远不会抛出不匹配的模式异常。


推荐阅读