简体   繁体   English

合并 haskell 中的两个列表

[英]Merge two lists in haskell

I get this function to merge two lists in haskell:我得到这个 function 来合并 haskell 中的两个列表:

merge :: [a] -> [a] -> [a]
merge xs     []     = xs
merge []     ys     = ys
merge (x:xs) (y:ys) = x : y : merge xs ys

but i want this function merge:: ([a],[a]) -> [a] , how do I make this change?但我想要这个 function merge:: ([a],[a]) -> [a] ,我该如何做这个改变?

There is an uncurry function, which can be helpful in such situations.有一个uncurry function,在这种情况下会很有帮助。 Quote:引用:

uncurry converts a curried function to a function on pairs. uncurry 将 curried function 转换为 function 对。

In this case, we can use it to derive merge' from merge :在这种情况下,我们可以使用它从merge派生merge'

merge' :: ([a], [a]) -> [a]
merge' = uncurry merge

merge' ([1],[2]) == [1, 2] --> True

You change你改变

merge1 :: [a] -> [a] -> [a]
merge1    xs     []   = xs
merge1    []     ys   = ys
merge1  (x:xs) (y:ys) = x : y : merge1 xs ys

to

merge2 :: ([a], [a]) -> [a]
merge2    ( xs, [] )  = xs
merge2    ( [], ys )  = ys
merge2   (x:xs, y:ys) = x : y : merge2 (xs, ys)

merge1 is known as a "curried" function, and merge2 as "uncurried". merge1被称为“curried” function, merge2被称为“uncurried”。

The functions curry and uncurry go between the two forms by packaging/unpackaging the arguments as needed while calling the given function:函数curryuncurry go 在两个 forms 之间通过打包/解包 arguments 在需要时调用给定的 ZC145DF145268E1683:

curry   f  x y  = f (x,y)
uncurry g (x,y) = g  x y

Thus merge1 = curry merge2 and merge2 = uncurry merge1 , but you have to actually define at least one of them to implement the actual functionality.因此merge1 = curry merge2merge2 = uncurry merge1 ,但您必须实际定义其中至少一个来实现实际功能。

You could reuse the merge function to make it work for tuples of lists as follows:您可以重用merge function 使其适用于列表元组,如下所示:

merge :: [a] -> [a] -> [a]
merge xs     []     = xs
merge []     ys     = ys
merge (x:xs) (y:ys) = x : y : merge xs ys

mergeTuples :: ([a], [a]) -> [a]
mergeTuples (xs, ys) = merge xs ys

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM