1

我想知道如何根据示例列表重新排序列表列表。这是一个澄清我的问题的例子:

["Foo", "Bar", "Something"] 

那是示例列表,现在我想重新排序下面显示的列表,只查看其中每个列表的头部:

[["Something", "one", "two", "three"], ["Foo", "four", "five", "six"], 
["Bar", "seven", "eight", "nine"]]

对此:

[["Foo", "four", "five", "six"], ["Bar", "seven", "eight", "nine"],
["Something", "one", "two", "three"]]

谢谢

编辑:

我尝试映射一个交换两个元素的交换函数,但这不起作用,因为我在这里处理两个列表。

4

3 回答 3

2

可能是一种非常粗暴的方法:

Prelude> let a = [["Something", "one", "two", "three"], ["Foo", "four", "five", "six"], ["Bar", "seven", "eight", "nine"]]
Prelude> let b = ["Foo", "Bar", "Something"]
Prelude> concatMap (\y -> filter (\(x:xs) -> x == y)  a) b
[["Foo","four","five","six"],["Bar","seven","eight","nine"],["Something","one","two","three"]]
于 2013-09-26T10:46:40.967 回答
0

基于列表理解的另一种解决方案可以是:

Prelude> let a = [["Something", "one", "two", "three"], ["Foo", "four", "five", "six"], ["Bar", "seven", "eight", "nine"]]
Prelude> let b = ["Foo", "Bar", "Something"]

Prelude> let c = [ y | x<-b, y<-a, x `elem` y ]

[["Foo","four","five","six"],["Bar","seven","eight","nine"],["Something","one","two","three"]]

您可以阅读本章以获取有关如何使用列表理解的更多说明:Lyah

于 2013-09-26T19:49:16.057 回答
0

您想根据自定义比较对列表进行排序。所以,让我们去做吧!基本比较函数应该查看索引值出现在示例列表中。

import Data.List

cmpIndex :: Eq a => [a] -> [a] -> [a] -> Ordering
cmpIndex example s1 s2 = compare (indexOf s1) (indexOf s2)
    where indexOf s = findIndex (head s ==) example

这有点危险——呼叫head总是一个暂停的原因。但是让我们假设你知道一些我不知道的事情并继续前进。我们将为输入命名以使测试更具可读性,然后启动 ghci:

example = ["Foo", "Bar", "Something"]
list = [["Something", "one", "two", "three"], ["Foo", "four", "five", "six"], ["Bar", "seven", "eight", "nine"]]

*Main> sortBy (cmpIndex example) list
[["Foo","four","five","six"],["Bar","seven","eight","nine"],["Something","one","two","three"]]
于 2013-09-27T06:00:06.000 回答