gpt4 book ai didi

haskell - 在 haskell 中加入或合并函数

转载 作者:行者123 更新时间:2023-12-02 17:37:52 25 4
gpt4 key购买 nike

Haskell 中是否有一个函数可以执行 SQL 连接或 R 合并的等效操作?

基本上我有两个元组列表,并想根据它们的键“压缩”它们。我知道每个键只有一个或零值

a = [(1, "hello"), (2, "world")]
b = [(3, "foo"), (1, "bar")]

得到类似的东西

 [ (Just (1, "hello), Just (1, "bar))
, (Just (2, "world), Nothing)
, (Nothing , Just (3, "foo"))
]

最佳答案

使用有序集(列表)Ord key

key = fst

fullOuterJoin xs [] = map (\x -> (Just x, Nothing)) xs
fullOuterJoin [] ys = map (\y -> (Nothing, Just y)) ys
fullOuterJoin xss@(x:xs) yss@(y:ys) =
if key x == key y
then (Just x, Just y): fullOuterJoin xs ys
else
if key x < key y
then (Just x, Nothing): fullOuterJoin xs yss
else (Nothing, Just y): fullOuterJoin xss ys

(复杂度为 O(n+m) 但如果您必须排序,则为 O(n log n + m log m))

例子

setA = [(1, "hello"), (2, "world")]
setB = [(1, "bar"), (3, "foo")]

*Main> fullOuterJoin setA setB
[(Just (1,"hello"),Just (1,"bar")),(Just (2,"world"),Nothing),(Nothing,Just (3, "foo"))]

(显然有 sort 支持

fullOuterJoin' xs ys = fullOuterJoin (sort xs) (sort ys)

正如@Franky 所说,您可以避免 if,例如

fullOuterJoin xs [] = [(Just  x, Nothing) | x <- xs]
fullOuterJoin [] ys = [(Nothing, Just y) | y <- ys]
fullOuterJoin xss@(x:xs) yss@(y:ys) =
case (compare `on` key) x y of
EQ -> (Just x, Just y): fullOuterJoin xs ys
LT -> (Just x, Nothing): fullOuterJoin xs yss
GT -> (Nothing, Just y): fullOuterJoin xss ys

关于haskell - 在 haskell 中加入或合并函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24424403/

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