Haskell中的zip函数

问题描述 投票:5回答:1

zip函数的实现,它将两个列表作为参数并返回一个新的对列表。到目前为止我得到了这个

myZip [] [] = []
myZip (x:xs) (y:ys) = [(x,y)] ++ myZip xs ys

任何帮助?

haskell recursion implementation
1个回答
6
投票

实际上只有一种方法可以为列表编写它,即使是作业:

zip :: [a] -> [b] -> [(a,b)]
zip (a:as) (b:bs) = (a,b) : zip as bs
zip _      _      = []

或者,更一般地说,

zipWith :: (a -> b -> c) -> [a]->[b]->[c]
zipWith f (a:as) (b:bs) = f a b : zipWith f as bs
zipWith _ _      _      = []

如果你想变得古怪,并使用流融合,流融合纸的版本,自动机风格,

zipWith :: (a -> b -> c) -> Stream a -> Stream b -> Stream c
zipWith f (Stream next0 sa0) (Stream next1 sb0) = Stream next (sa0, sb0, Nothing)
  where
    next (sa, sb, Nothing) = case next0 sa of
        Done        -> Done
        Skip    sa' -> Skip (sa', sb, Nothing)
        Yield a sa' -> Skip (sa', sb, Just a)

    next (sa', sb, Just a) = case next1 sb of
        Done        -> Done
        Skip    sb' -> Skip          (sa', sb', Just a)
        Yield b sb' -> Yield (f a b) (sa', sb', Nothing)
© www.soinside.com 2019 - 2024. All rights reserved.