gpt4 book ai didi

haskell - 与分数相关的类型错误

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

我正在尝试找出问题所在。看起来类型有问题,但单独使用相同的表达式就可以正常工作。

这是代码:

a = [9, 4, 12, 0, -6, 16] :: [Int]

qsort:: [Int] -> [Int]
qsort [] = []
qsort [x] = [x]
qsort xs = (qsort l)++(qsort r)
where m = (realToFrac(sum xs)) / (realToFrac(length xs))
l = filter (<=m) xs
r = filter (>m) xs

main::IO()
main = do
print (show (qsort a))

它抛出:

main.hs:7:36:
No instance for (Fractional Int)
arising from a use of `/'
Possible fix: add an instance declaration for (Fractional Int)
In the expression: (realToFrac (sum xs)) / (realToFrac (length xs))
In an equation for `m':
m = realToFrac (sum xs) / (realToFrac (length xs))
In an equation for `qsort':
qsort xs
= (qsort l) ++ (qsort r)
where
m = realToFrac (sum xs) / (realToFrac (length xs))
l = filter (<= m) xs
r = filter (> m) xs

但是效果很好:

a = [9, 4, 12, 0, -6, 16] :: [Int]
main::IO()
main = do
print (show ( (realToFrac(sum a)) / (realToFrac(length a)) ))

最佳答案

您的m定义给出了一些Fractional类型。但是,您在 lr 的定义中将 mInt 进行比较,这会让编译器感到困惑。下面的方法就可以解决这个问题:

a = [9, 4, 12, 0, -6, 16] :: [Int]

qsort:: [Int] -> [Int]
qsort [] = []
qsort [x] = [x]
qsort xs = (qsort l)++(qsort r)
where m = realToFrac(sum xs) / (realToFrac(length xs))
l = filter ((<=m) . fromIntegral) xs
r = filter ((>m) . fromIntegral) xs

main::IO()
main = do
print (show (qsort a))

关于haskell - 与分数相关的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14941104/

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