使用foldr实现zip [英] Implement zip using foldr

查看:75
本文介绍了使用foldr实现zip的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正处于真实世界Haskell的第4章,我正试图围绕着在foldr方面实现foldl



(这里是他们的代码:)

  myFoldl ::(a  - > b  - > a) - > a  - > [b]  - > a 

myFoldl fz xs = foldr步骤编号xs z
其中step xga = g(传真)

我想我会尝试使用相同的技术来实现 zip ,但我似乎没有取得任何进展。它甚至有可能吗?

解决方案

  zip2 xs ys = foldr step done xs ys 
where done ys = []
step x zipsfn [] = []
step x zipsfn(y:ys)=(x,y):(zipsfn ys)

这是如何工作的:(foldr step done xs)返回一个函数,它消耗
ys;所以我们沿着xs列表建立一个嵌套的
函数,它们将被应用到ys的相应部分。

它:我从一般想法开始(从之前看过的类似
的例子开始),写道:

pre $ lt; code> zip2 xs ys = foldr步骤完成xs ys

然后依次填入以下每一行,并使用
是为了使类型和数值正确。
最容易考虑最简单的情况,而不是更困难的情况。

第一行可以写得更简单:

  zip2 = foldr步骤完成

作为mattiast显示。


I'm currently on chapter 4 of Real World Haskell, and I'm trying to wrap my head around implementing foldl in terms of foldr.

(Here's their code:)

myFoldl :: (a -> b -> a) -> a -> [b] -> a

myFoldl f z xs = foldr step id xs z
    where step x g a = g (f a x)

I thought I'd try to implement zip using the same technique, but I don't seem to be making any progress. Is it even possible?

解决方案

zip2 xs ys = foldr step done xs ys
  where done ys = []
        step x zipsfn []     = []
        step x zipsfn (y:ys) = (x, y) : (zipsfn ys)

How this works: (foldr step done xs) returns a function that consumes ys; so we go down the xs list building up a nested composition of functions that will each be applied to the corresponding part of ys.

How to come up with it: I started with the general idea (from similar examples seen before), wrote

zip2 xs ys = foldr step done xs ys

then filled in each of the following lines in turn with what it had to be to make the types and values come out right. It was easiest to consider the simplest cases first before the harder ones.

The first line could be written more simply as

zip2 = foldr step done

as mattiast showed.

这篇关于使用foldr实现zip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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