0

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

我做了这个:

编辑:我已经重写了这样的primefunction和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

有人能帮我吗?

亲切的问候,

4

1 回答 1

3

不完整的模式是因为您省略了 when 的情况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)

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

于 2012-08-20T13:42:22.007 回答