gpt4 book ai didi

haskell - 如何编写这些函数以独立于类型 : Int vs Integer 的选择

转载 作者:行者123 更新时间:2023-12-02 10:48:05 24 4
gpt4 key购买 nike

我正在处理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)

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

最佳答案

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

关于haskell - 如何编写这些函数以独立于类型 : Int vs Integer 的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7302643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com