作者:mobiledu2502928947 | 来源:互联网 | 2023-02-03 13:13
我正在尝试编写一个Erasthosthenes函数的筛子,它将用户的所有素数从2增加到他的上限.所以我写了这段代码:
main = do
putStrLn "Upper Limit"
g <- readLn
let sieve [] = []
let sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p /= 0]
let primes = sieve [2..g]
print primes
代码编译并给我正确的解决方案,但我在解决方案的最后得到了这个例外:***例外:功能筛的非详尽模式所以我检查了哪些模式不匹配.
warning: [-Wincomplete-patterns]
Pattern match(es) are non-exhaustive
In an equation for `sieve': Patterns not matched: (_:_)
warning: [-Wincomplete-patterns]
Pattern match(es) are non-exhaustive
In an equation for `sieve': Patterns not matched: []
至极我不明白,因为我已经给了let sieve [] = []
我以为_哈斯克尔是指任何变量,这样是什么模式(:)是什么意思?任何帮助,将不胜感激.
1> Willem Van O..:
问题是您在两个单独的语句中定义sieve
let
.因此,Haskell编译器认为您定义了两个单独的sieve
函数.因此,第一个sieve
缺乏(_:_)
模式而后者缺乏[]
模式.
如果您以后使用sieve
,Haskell编译器将链接到最近的一个,因此后者(因此调用sieve
)let primes = sieve [2..g]
将只知道第二个 sieve
定义(因此将在列表的末尾出错).
您可以使用以下let
语句解决此问题:
let { sieve [] = [] ; sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p /= 0] }