gpt4 book ai didi

Haskell - sortBy 函数

转载 作者:行者123 更新时间:2023-12-03 23:21:10 28 4
gpt4 key购买 nike

我有一个向量列表。但现在我想使用 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)])

最佳答案

你只需写:

sortBy (comparing vectorLength) ....

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

写出来,你想要的是:
sortBy comparVectors listofvectors
where comparVectors a b = vectorLength a `compare` vectorLength b

关于Haskell - sortBy 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5965326/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com