解析模式错误

时间:2012-02-16 16:23:51

标签: haskell

尝试实现一个返回一个int列表的函数,表示每个双精度列表的排序,例如:

orderings [ [1.0, 2.0, 3.0], [3.0, 2.0, 1.0] ]
> [ [0, 1, 2], [2, 1, 0] ]

但是,出于某种原因我的模式匹配有问题:

import Data.List

-- Return a list of orderings for each list of doubles
orderings:: [[Double]] -> [Int]
orderings [] = []
orderings x:xs = (ordering x):(orderings xs)

ordering:: [Double] -> [Int]
ordering xs = [i | (i, _) <- sorted] where
    sorted = sortBy (\(i1, e1) (i2,e2) -> compare e1 e2) $ zip [0..] xs

错误是:

Parse error in pattern: orderings

看不到我生命中的错误!

4 个答案:

答案 0 :(得分:5)

另外两个问题(除x:xs周围的缺失括号外):

  1. orderings的类型错误;我怀疑它应该是[[Double]] -> [[Int]]

  2. x不在ordering范围内;我怀疑它应该是xs

  3. 以下是更正后的代码:

    import Data.List
    
    -- Return a list of orderings for each list of doubles
    orderings:: [[Double]] -> [[Int]]  -- changed type
    orderings [] = []
    orderings (x:xs) = (ordering x):(orderings xs)
    
    ordering:: [Double] -> [Int]
    ordering xs = [i | (i, _) <- sorted] where
        sorted = sortBy (\(i1, e1) (i2,e2) -> compare e1 e2) $ zip [0..] xs -- xs not x!
    

答案 1 :(得分:3)

如前所述,orderings的结果应为[[Int]]。但是,函数的实现可以简化为:

import Data.List

-- Return a list of orderings for each list of doubles
orderings :: [[Double]] -> [[Int]]
orderings = map ordering

ordering :: [Double] -> [Int]
ordering = map snd . sort . flip zip [0..]

答案 2 :(得分:2)

您必须在x:xs模式周围添加括号:

orderings (x:xs) = ...

答案 3 :(得分:0)

有3个错误:

orderings x:xs = (ordering x):(orderings xs)行中你试图将(:)列表和列表(但是利弊生成列表,前面给定的值),你忘记了x:xs周围的parens利弊模式匹配。

:的类型是:

Prelude> :type (:)
(:) :: a -> [a] -> [a]

该行的正确形式是:

orderings (x:xs) = (ordering x) ++ (orderings xs)

因为++汇总到列表:

Prelude> :type (++)
(++) :: [a] -> [a] -> [a]

最后一个错误是在最后一行,它应该是xs而不是x