【问题标题】:How do I properly use the length function in haskell?如何正确使用haskell中的长度函数?
【发布时间】:2022-01-11 06:11:48
【问题描述】:

我目前正在努力尝试在 haskell 中查找范围之间的素数。程序正确打印出素数范围。例如 countPrimesUntil 2 10 将打印出 [2, 3, 5, 7]。我正在寻找数字 4,因为这是 2 到 10 之间的素数。如何正确合并 countPrimes?

import Data.List

countPrimesUntil :: Integral a=> a -> a -> [a]
countPrimesUntil a b = takeWhile (<= b) $ dropWhile (< a) $ sieve [2..]
    while sieve (n:ns) = n:sieve [m | m <- ns, m `mod` n /= 0]

countPrimes n = length([x | x <- [2..n], countPrimesUntil x])

【问题讨论】:

  • while 应该是where

标签: haskell functional-programming primes


【解决方案1】:

countPrimesUntil 命名错误;它不算什么。相反,它会生成一个介于 ab 之间的素数列表。

当给定参数2n 时,您只需将length 应用于countPrimesUntil 的结果。

countPrimes n = length (countPrimesUntil 2 n)
-- countPrimes = length . countPrimesUntil 2

【讨论】:

    【解决方案2】:

    在这种情况下,countPrimes 调用countPrimesUntil 2 n,并确定它的长度,所以:

    countPrimes n = length (<strong>countPrimesUntil 2 n</strong>)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-05
      相关资源
      最近更新 更多