gpt4 book ai didi

haskell - Haskell 中的类型问题

转载 作者:行者123 更新时间:2023-12-02 10:34:46 25 4
gpt4 key购买 nike

我在 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

最佳答案

我已经找到了让代码编译的修改方案,但它实际上并没有找到素数。我必须改变

fromInteger (`sqrt` number)

floor $ sqrt $ fromIntegral number

函数名称周围的反引号符号是将其转换为某种中缀“运算符”,因此您可以这样做

mod x y

x `mod` y

但不是

`mod` x y

接下来,您使用 fromInteger 而不是 fromIntegral,后者适用于 Int(Int) code> 和 Integer 是不同的类型)。最后,我在 checkDiv 的第二个守卫中从 number 中删除了 floor,因为 number 已经是一个 整数

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 17),它将执行

checkDiv 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 是质数!您看到您的算法哪里做错了吗?

关于haskell - Haskell 中的类型问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19322363/

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