【问题标题】:How can I write these functions to be independent of choice of type: Int vs Integer我如何编写这些函数以独立于类型的选择:Int vs Integer
【发布时间】:2011-11-10 06:51:27
【问题描述】:

我正在处理Project Euler,很多问题都涉及类似的功能,例如计算素数列表。我知道使用 Integer 的计算比 Int 慢,所以我想编写函数来处理两者,这取决于我正在使用的数字的大小。

module Primes
(
    isPrime
    ,prime 
    ,allPrimes
)
where

import Data.List

isPrime :: Int -> Bool
isPrime n
    | n == 0 = False
    | n == 1 = False
    | n < 0 = isPrime (-n)
    | n < 4 = True
    | n `mod` 2 == 0 = False
    | n `mod` 3 == 0 = False
    | any ( (==0) . mod n ) [5..h] = False
    | otherwise = True
    where
        h = ( ceiling . sqrt . fromIntegral ) n


allPrimes :: [Int]
allPrimes = [ x | x<- [2..], isPrime x ]

prime :: Int -> Int
prime n = allPrimes !! (n-1)

我知道这段代码通常不是最理想的。我只是对如何使整数类型更通用感兴趣。

【问题讨论】:

  • 我在hpaste.org/50988(如果您有兴趣的话)上发布了对isPrime 的简短代码审查(重点是保留此处介绍的确切算法)。

标签: haskell types integer


【解决方案1】:

对于这类问题的更通用的解决方案,您可以尝试让您的代码在没有显式类型声明的情况下进行编译。 Haskell 将假定最通用的类​​型,您可以通过例如在 GHCi 上加载文件并执行 :t myFunctionName

来找出它是什么

【讨论】:

    【解决方案2】:

    试试Integral,它应该允许同时支持IntInteger

    【讨论】:

    • 听起来不错。我无法在不丢失所有格式的情况下粘贴实际代码,但我将签名替换为:isPrime :: (Integral n) => n -> Bool allPrimes :: (Integral n) => [n] prime :: (积分 n,积分 m) => n -> m,我收到此错误:“Primes.hs:29:24: 无法匹配预期类型 Int' against inferred type n' n' is a rigid type variable bound by the type signature for prime' at Primes.hs:28: 19"
    • @Peter Hall (!!) 函数采用 Int 参数。 prime 的类型应为 Integral n =&gt; Int -&gt; n
    猜你喜欢
    • 2011-12-19
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 2019-08-09
    相关资源
    最近更新 更多