Haskell中的类型问题

时间:2013-10-11 15:55:52

标签: haskell types casting

我对Haskell中的不同类型有一些问题,我该如何解决?

无法将预期类型Integer与实际类型Int -> t0 -> t0

匹配

由于

isPrime :: Int -> Bool
isPrime number
    | (number == 1) || (number == 2) = True
    | even number = False
    | otherwise = checkDiv number (fromInteger (`sqrt` number))

checkDiv :: Int -> Int -> Bool
checkDiv number divisor 
    | number == 2 = True
    | (floor number `mod` divisor) == 0 = False
    | otherwise = checkDiv number $ divisor - 1

1 个答案:

答案 0 :(得分:7)

我已经找到了修改以获得编译代码,但它实际上并没有找到素数。我不得不改变

fromInteger (`sqrt` number)

floor $ sqrt $ fromIntegral number

函数名称周围的反引号表示法是将其转换为各种类型的中缀“运算符”,所以你可以这样做

mod x y

x `mod` y

但不是

`mod` x y

接下来,您使用的是fromInteger而不是fromIntegral,这是Int上的Int Integerfloor不同的类型。最后,我从number的第二个后卫checkDiv中删除了number,因为Int已经是isPrime :: Int -> Bool isPrime number | (number == 1) || (number == 2) = True | even number = False | otherwise = checkDiv number (floor $ sqrt $ fromIntegral number) checkDiv :: Int -> Int -> Bool checkDiv number divisor | number == 2 = True | (number `mod` divisor) == 0 = False | otherwise = checkDiv number $ divisor - 1

checkDiv 17 4

因此,让我们通过您的代码,以便您可以看到正在发生的事情。如果我要计算4floor $ sqrt $ fromIntegral 17checkDiv 17 4 | 17 == 2 No | 17 `mod` 4 == 0 No | otherwise = checkDiv 17 (4 - 1) = checkDiv 17 3 checkDiv 17 3 | 17 == 2 No | 17 `mod` 3 == 0 No | otherwise = checkDiv 17 (3 - 1) = checkDiv 17 2 checkDiv 17 2 | 17 == 2 No | 17 `mod` 2 == 0 No | otherwise = checkDiv 17 (2 - 1) = checkDiv 17 1 checkDiv 17 1 | 17 == 2 No | 17 `mod` 1 == 0 Yes = False ),它会执行

17

但{{1}}是素数!你看到算法在哪里做错了吗?