尝试实现一个返回一个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
看不到我生命中的错误!
答案 0 :(得分:5)
另外两个问题(除x:xs
周围的缺失括号外):
orderings
的类型错误;我怀疑它应该是[[Double]] -> [[Int]]
x
不在ordering
范围内;我怀疑它应该是xs
以下是更正后的代码:
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