【问题标题】:Non-exhaustive patterns in function defined in GHCiGHCi 中定义的函数中的非详尽模式
【发布时间】:2017-10-21 04:03:59
【问题描述】:

我正在尝试编写一个 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 [] = [] 我认为 Haskell 中的 _ 表示任何变量,那么模式 (:) 是什么意思? 任何帮助将不胜感激。

【问题讨论】:

标签: haskell exception ghci


【解决方案1】:

问题在于您在两个单独的let 语句中定义了sieve。因此,Haskell 编译器认为您定义了两个独立的sieve 函数。因此第一个sieve 缺少(_:_) 模式,而后者缺少[] 模式。

如果您稍后使用sieve,Haskell 编译器将链接到最近的编译器,因此let primes = sieve [2..g] 中的后者(因此调用sieve)只会知道第二个 em> sieve 定义(因此会在列表末尾出错)。

您可以使用以下let 语句解决此问题:

let { sieve [] = [] ; sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p /= 0] }

【讨论】:

  • 您还可以在let之后将定义的两个部分缩进到同一级别。
猜你喜欢
  • 2019-01-25
  • 2021-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多