我正在 Haskell 中寻找一个函数来压缩两个长度可能不同的列表.我能找到的所有 zip 函数只是删除比另一个长的列表的所有值.
I'm looking for a function in haskell to zip two lists that may vary in length. All zip functions I could find just drop all values of a lists that is longer than the other.
例如:在我的练习中,我有两个示例列表.如果第一个比第二个短,我必须使用 0 填充.否则我必须使用 1.我不允许使用任何递归.我只需要使用高阶函数.
For example: In my exercise I have two example lists. If the first one is shorter than the second one I have to fill up using 0's. Otherwise I have to use 1's. I'm not allowed to use any recursion. I just have to use higher order functions.
有什么我可以使用的功能吗?到目前为止,我真的找不到任何解决方案.
Is there any function I can use? I really could not find any solution so far.
推荐答案您可以将 0 或 1 的 inifinte 列表附加到每个列表中,然后从结果压缩列表中获取您需要的数字:
You can append an inifinte list of 0 or 1 to each list and then take the number you need from the result zipped list:
zipWithDefault :: a -> b -> [a] -> [b] -> [(a,b)] zipWithDefault da db la lb = let len = max (length la) (length lb) la' = la ++ (repeat da) lb' = lb ++ (repeat db) in take len $ zip la' lb'更多推荐
使用默认值压缩而不是删除值?
发布评论