首页 > 解决方案 > 用 zipWith 写 zip

问题描述

我正在通过 Chris Allen 和 Julie Moronuki 的 Haskell Programming 一书学习 Haskell。需要有关压缩列表练习之一的帮助。该练习有 3 个部分,前两个是关于编写我们自己的 zip 和 zipWith 实现,我能够做到。

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

myZipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
myZipWith _ _ [] = []
myZipWith _ [] _ = []
myZipWith f (x:xs) (y:ys) = (f x y) : myZipWith f xs ys

最后一部分要求用 zipWith 编写 zip。我无法提出解决方案。老实说,我无法完全掌握这个问题(用第二个函数编写一个函数,当不需要第二个函数应用时,因为它首先需要所有参数)。谢谢您的帮助。

标签: haskell

解决方案


myzip1和之间的唯一区别myZipWith

myzip1      (x:xs) (y:ys) =   (x,y) : myzip1      xs ys
myZipWith f (x:xs) (y:ys) = (f x y) : myZipWith f xs ys

也许对某些人myzip1来说myZipWith f是一样的f

myzip1 = myZipWith f

f怎样

(f x y) = (x, y)

推荐阅读