gpt4 book ai didi

haskell - Haskell 中的 zip 函数

转载 作者:行者123 更新时间:2023-12-04 14:34:10 24 4
gpt4 key购买 nike

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

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

有什么帮助吗?

最佳答案

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

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)

关于haskell - Haskell 中的 zip 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5776322/

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