2

我试图找出问题所在。似乎类型有问题,但单独使用相同的表达式可以正常工作。

这是代码:

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

3 回答 3

6

您的m定义给出了一些 type 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))
于 2013-02-18T16:45:49.493 回答
5

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

要解决您的问题,您可以使用整数除法 ( div) 或将列表中的整数转换为小数,然后再将它们与m.

于 2013-02-18T16:47:09.313 回答
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

于 2013-02-18T16:56:16.610 回答