Haskell - sortBy函数

时间:2011-05-11 13:48:51

标签: haskell

我有一个向量列表。但现在我想使用sortBy函数按照它们的长度对这个向量列表进行排序。我已经是:

import Data.List

vectorLength::(Int,Int)->Float
vectorLength(x,y) = sqrt(fromIntegral ((x^2)+(y^2)))

sortVectors::[(Int, Int)]->[(Int, Int)]
sortVectors list = sortBy(map vectorLength list) list

main = do
    print(map vectorLength [(1,4), (2,6), (-2, -8), (3, -4)])
    print(sortVectors[(1,4), (2,6), (-2,-8), (3, -4)])

vectorLength函数确实有效。

map vectorLength [(1,4), (2,6), (-2,-8),(3,-4)]   
output: [4.1231055, 6.3245554, 8.246211, 5.0]

我想在调用以下函数时

sortVectors [(1,4), (2,6), (-2,-8), (3,-4)]  
output: [(-2,-8), (2,6), (3,-4), (1,4)]

但是我收到以下错误:

Couldn't match expected type `(Int, Int)' with actual type `[a0]'
    Expected type: (Int, Int) -> (Int, Int) -> Ordering
      Actual type: [a0] -> [b0]
    In the return type of a call of `map'
    In the first argument of `sortBy', namely `(map vectorLength list)'
    In the expression: sortBy (map vectorLength list) list

感谢您的帮助。 这是我的解决方案

import Data.List

vectorLength::(Int,Int)->Float
vectorLength(x,y) = sqrt(fromIntegral ((x^2)+(y^2)))

sortVectors::[(Int, Int)]->[(Int, Int)]
sortVectors list = rever(sortBy compareVectors list)

rever::[(Int, Int)]->[(Int, Int)]
rever [] = []
rever (x:xs) = rever xs ++ [x]

compareVectors::(Int, Int) ->(Int, Int) ->Ordering
compareVectors(a,b) (c,d) 
    | vectorLength(a,b) < vectorLength(c,d) = LT
    | vectorLength(a,b) > vectorLength(c,d) = GT

main = do
    print(map vectorLength [(1,4), (2,6), (-2, -8), (3, -4)])
    print(sortVectors[(1,4), (2,6), (-2,-8), (3, -4)])

2 个答案:

答案 0 :(得分:18)

你只需写:

sortBy (comparing vectorLength) ....

您将列表作为sortBy的第一个元素,但需要一个函数。

要写出来,你想要的是:

sortBy comparVectors listofvectors
    where comparVectors a b = vectorLength a `compare` vectorLength b

答案 1 :(得分:8)

Perl人将Schwartzian_transform

称为以下模式

只需将列表更改为键值对列表,然后按键排序。 (如果它很昂贵,这可以避免关键功能的额外计算)

sortByKey keyf xs =
    let k_xs = map (\x-> (keyf x, x)) xs in
    let sorted = sortBy (compare `on` fst) k_xs in
    map snd sorted

sortByKey vectorLength vectors