我的修改版本的zip有什么问题? [英] What's wrong with my altered version of zip?

查看:98
本文介绍了我的修改版本的zip有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个类似于zip的函数,但不会丢弃额外的元素。

I'm trying to write a function that is similar to zip but that won't discard extra elements. I feel like I've made a really dumb error somewhere.

输入示例:

zipMaybe [1,2,3] [1,2]

[(Just 1, Just 1), (Just 2, Just 2), (Just 3, Nothing)]







zipMaybe :: [a] -> [b] -> [(Maybe a, Maybe b)]
zipMaybe (a:as) (b:bs) = (Just a, Just b) : zip as bs -- line with error
zipMaybe (a:as) [] = (Just a, Nothing) : zip as []
zipMaybe [] (b:bs) = (Nothing, Just b) : zip [] bs
zipMaybe _ _ = []

这将无法编译。

Test.hs:2:49:
    Couldn't match type `a' with `Maybe a'
      `a' is a rigid type variable bound by
          the type signature for
            zipMaybe :: [a] -> [b] -> [(Maybe a, Maybe b)]
          at Test.hs:1:13
    Expected type: [Maybe a]
      Actual type: [a]
    In the first argument of `zip', namely `as'
    In the second argument of `(:)', namely `zip as bs'
    In the expression: (Just a, Just b) : zip as bs


推荐答案

您应该调用 zipMaybe 递归,而不是退回到 zip (类型错误)。

You should call zipMaybe recursively instead of backing off to vanilla zip, which has the wrong type.

zipMaybe :: [a] -> [b] -> [(Maybe a, Maybe b)]
zipMaybe (a:as) (b:bs) = (Just a, Just b) : zipMaybe as bs
zipMaybe (a:as) [] = (Just a, Nothing) : zipMaybe as []
zipMaybe [] (b:bs) = (Nothing, Just b) : zipMaybe [] bs
zipMaybe _ _ = []

Btw。这个函数的定义较短:

Btw., there's a shorter definition of this function:

zipMaybe (x:xs) (y:ys)  =  (Just x, Just y) : zipMaybe xs ys
zipMaybe xs     []      =  [(Just x, Nothing) | x <- xs]
zipMaybe []     ys      =  [(Nothing, Just y) | y <- ys]

这篇关于我的修改版本的zip有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆