gpt4 book ai didi

haskell - 使用 sortBy 对列表进行排序

转载 作者:行者123 更新时间:2023-12-02 06:13:20 30 4
gpt4 key购买 nike

我正在尝试根据每个元组中的第 4 个元素对我的元组列表进行排序。第四个元素包含一个人名字符串。我想将包含相同名称的元组放在一起。排序前的元组列表示例如下:

[("A",100,"Q",3,"Todd",2.0),
("B",203,"R",3,"Rachel",1.66),
("B",273,"F",1,"Mike",2.66),
("A",200,"P",1,"Rachel",0.0),
("A",549,"D",3,"Todd",2.0),
("B",220,"S",3,"Todd",4.0),
("B",101,"M",3,"Jon",3.33),
("A",999,"N",3,"Rachel",1.33)]

我也希望它看起来像:

[("A",100,"Q",3,"Todd",2.0),
("A",549,"D",3,"Todd",2.0),
("B",220,"S",3,"Todd",4.0),
("B",203,"R",3,"Rachel",1.66),
("A",200,"P",1,"Rachel",0.0),
("A",999,"N",3,"Rachel",1.33),
("B",273,"F",1,"Mike",2.66),
("B",101,"M",3,"Jon",3.33)]

我需要让所有包含 Todd 的元组彼此相邻,以此类推。名称显示的顺序无关紧要,只要它们彼此相邻即可。

sortedList= show . sortBy byName . (map stringToTuple) . (map words) . lines

这是我调用排序依据的代码行。我知道我需要创建一个函数 byName 以某种方式确定元组是否共享一个通用名称。

任何帮助引导我进入编写 byName 方法的正确方向将不胜感激。谢谢

最佳答案

sortBy 类型开始:

> :t sortBy
sortBy :: (a -> a -> Ordering) -> [a] -> [a]

这意味着 byName 需要具有类型 a -> a -> Ordering 。在这种情况下, a 是一个元组,其第五个元素的类型为 StringbyName 将忽略其他字段。所以你需要定义一个函数,比如

type MyType = (String, Int, String, Int, String, Double)
byName :: MyType -> MyType -> Ordering
byName (_, _, _, _, a, _) (_, _, _, _, b, _) = ...

我将把 ... 替换为正确的表达式作为练习。

(Recall that Ordering is a type with three values, LT , EQ , and GT , where byName a b == LT if a < b , byName a b == EQ if a == b , and byName a b == GT if a > b . In your case, two tuples will compare as equal as long as they have同名。听起来您实际上并不关心 byName 是否返回 LTGT 否则。)

关于haskell - 使用 sortBy 对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52506258/

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