输入与分数相关的错误

时间:2013-02-18 16:41:33

标签: haskell types

我试图弄清楚什么是错的。似乎类型有问题,但同样的表达单独工作正常。

以下是代码:

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))   ))

3 个答案:

答案 0 :(得分:6)

您的m定义会提供多种类型Fractional。 但是,您在mInt的定义中将lr进行了比较,这会混淆编译器。 以下将解决这个问题:

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))

答案 1 :(得分:5)

realToFrac(sum xs) / (realToFrac(length xs))确实有效,但其结果是一个小数。因此,在您的代码中m是一个小数。但是,您将m与列表中的项目进行比较,这些项目是Ints。由于您只能比较相同类型的值而Ints不是小数,这会导致类型错误。

要解决您的问题,您可以使用整数除法(div)或将列表中的整数转换为小数,然后再将其与m进行比较。

答案 2 :(得分:1)

您可以使用x作为支点。列表模式匹配“qsort(x:xs)”在这里有很多帮助。

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

qsort:: [Int] -> [Int]                                                                                                
qsort [] = []                                                                                                         
qsort (x:xs) = (qsort l) ++ [x] ++ (qsort r)                                                                           
    where   l = filter (<=x) xs                                                                                       
            r = filter (>x) xs                                                                                        

main::IO()                                                                                                            
main = putStrLn $ show $ qsort a   

 -- *Main> main                                                                                                           
 -- [-6,0,4,9,12,16] 

替代语法:http://hpaste.org/81793