gpt4 book ai didi

haskell - 如何压缩不同长度的列表?

转载 作者:行者123 更新时间:2023-12-03 01:34:50 24 4
gpt4 key购买 nike

如何压缩两个列表,例如

["Line1","Line2","Line3"]
["Line4","Line5"]

不丢弃第一个列表中的其余元素?

如果可以的话,我想用空列表压缩额外的元素。

最佳答案

zipWithPadding :: a -> b -> [a] -> [b] -> [(a,b)]
zipWithPadding a b (x:xs) (y:ys) = (x,y) : zipWithPadding a b xs ys
zipWithPadding a _ [] ys = zip (repeat a) ys
zipWithPadding _ b xs [] = zip xs (repeat b)

只要有元素,我们就可以简单地对它们进行压缩。一旦我们用完元素,我们只需使用填充元素的无限列表来压缩剩余列表。

在您的情况下,您可以将其用作

zipWithPadding "" "" ["Line1","Line2","Line3"] ["Line4","Line5"]
-- result: [("Line1","Line4"),("Line2","Line5"),("Line3","")]

关于haskell - 如何压缩不同长度的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22403029/

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