Haskell程序提供了非常优质的数字

时间:2012-08-20 13:12:55

标签: haskell

我制作了一个计算相当素数的haskell程序。漂亮素数是非常接近2的幂的素数。你给出2个数字例如:10和20然后它返回17因为17最接近2的幂.17 - 16 = 1所以它是最接近的。

我已经做到了:

编辑:我已经重写了这样的功能和e verw功能,但仍然得到-1。

  -- Geeft priemgetallen terug tussen de 2 grenzen
-- English: Gives primenumbers between 2 numbers
priemgetallen :: Int->[Int]
priemgetallen b = take b (zeef [2..])
    where zeef (p:xs) = p : zeef [x | x<-xs, (mod x p) /= 0]

-- Geeft machten terug tussen de 2 grenzen
-- English: Gives powers of 2 between 2 numbers
machten :: Int->Int->[Int]
machten a b 
        | a <= 2 = 2:[2^x| x<-[2..b], (2^x) `mod` 2 == 0, 2^x < b, 2^x > a]
        | otherwise = [2^x| x<-[2..b], (2^x) `mod` 2 == 0, 2^x < b, 2^x > a]

-- English: the start of the function
prettyprime :: Int->Int->Int
prettyprime a b = vergelijk ( verw a (priemgetallen b)) (machten a b)

-- Filter the list
verw :: Int->[Int]->[Int]
verw _ [] = []
verw k (x:xs)
    | x > k = [x] ++ verw k xs
    | otherwise = verw k xs

-- Vergelijkt alle priemgetallen en geeft welke korste bij het ander ligt
-- English this function must see what primenumber is the closest to a power of 2 but I can't fix it
vergelijk :: [Int]->[Int]->Int
vergelijk [] _ = -1
vergelijk _ [] = -1
vergelijk (x:xs) (y:ys)
            | x - y < vergelijk (x:xs) ys = x
            | x - y > vergelijk (x:xs) ys = vergelijk xs (y:ys)
            | x - y == vergelijk (x:xs) ys = x




main = do
       print $ prettyprime 14 20

有人可以帮助我吗?

亲切的问候,

1 个答案:

答案 0 :(得分:3)

不完整的模式是因为你在x - y == vergelijk (x:xs) ys时省略了这种情况。如果您添加-fwarn-incomplete-patterns并将您的警卫转换为真实case,编译器就会向您发出警告:

vergelijk (x:xs) (y:ys) = case compare (x - y) (vergelijk (x:xs) ys) of
    LT -> x
    -- you will get a warning about having no case for EQ
    GT -> vergelijk xs (y:ys)

作为奖励,此版本不太可能重新计算递归调用,尤其是在低优化级别时。