我有两个列表["a","b","c","d"]
和["b","d","a","c"]
如何使用与第二个列表相同的顺序创建一个命令第一个列表的函数?
在这个例子中是这样的:
> ord ["a","b","c","d"] ["b","d","a","c"]
["b","d","a","c"]
我所做的所有功能都给了我一个不完整的清单:
ord :: [String] -> [String] -> [String]
ord [] _ = []
ord (h:t) (x:xs) | (h==x) = h:(ord t xs)
| otherwise = ord t (x:xs)
这只是一个例子;我不能简单地提出第二个清单。
答案 0 :(得分:3)
这是一个快速而肮脏的解决方案,它通过将第一个列表中的每个字符串按第二个中的顺序(我还重命名为ord
到orderThese
)来构建结果:
orderThese :: [String] -> [String] -> [String]
orderThese _ [] = []
orderThese as (b:bs) = filter (\x -> x == b) as ++ orderThese as bs
例如,orderThese ["a", "c", "a", "b"] ["b", "a", "c"]
会返回["b","a","a","c"]
。
答案 1 :(得分:1)
我认为这就是你想要的:
import Data.Function (on)
import Data.List (elemIndex, sortBy)
ord :: Eq a => [a] -> [a] -> [a]
ord listToSort desiredOrder = sortBy (compare `on` (`elemIndex` desiredOrder)) listToSort
我建议
ord
中有一个名为Data.Char
的函数;和desiredOrder
而不是listToSort
的函数。