[plt-dev] Re: Is there an idiom for throwing away some values?

From: Eli Barzilay (eli at barzilay.org)
Date: Tue Jul 28 04:54:55 EDT 2009

On Jul 28, Noel Welsh wrote:
> On Tue, Jul 28, 2009 at 5:09 AM, Eric Hanchrow<eric.hanchrow at gmail.com> wrote:
> >        (for/fold ([sum 0]
> >                   [factor 1])
> 
> ...
> 
> I run into this all the time: writing a for/fold where I only want
> one value at the end. I've thought about implementing for/fold/first
> (returns only the first accumulator) but haven't got around to it.
> I tend to write
> 
> (define-values (sum _)
>   (for/fold ...))

Actually, I ran into this too, but not too many times.  In any case,
looking at the macros, it looks like doing the `for/fold/first' thing
is easy -- just change (values* fold-var ...) to return the first one
only, right?  If so, then the first patch below adds `for/fold/first'
with the 3 variants (`for*' and the derived thing).  (It's a patch
against the svn head, since I reformatted the code first.)

But looking at that, I realized that it's even easier to do accept an
expression to return, so the second patch implements this a `#:return'
that specifies the return expression, so Eric's function can be
written as

  (define (series x)
    (for/fold ([sum 0] [factor 1])
              ([n (in-range 20)])
              #:return sum
      (values (+ sum factor)
              (* factor (/ x (add1 n))))))

This is the second patch.

It might make more sense to put the #:return after the initial binding
list (to make the scope more obvious), or add some `for/fold/return'.
I prefer the keyword version, since more forms get the benefit without
requiring more .../return variants.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: for-fold-first
Type: application/octet-stream
Size: 8506 bytes
Desc: not available
URL: <http://lists.racket-lang.org/dev/archive/attachments/20090728/0142f29c/attachment.obj>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: for-fold-return
Type: application/octet-stream
Size: 5186 bytes
Desc: not available
URL: <http://lists.racket-lang.org/dev/archive/attachments/20090728/0142f29c/attachment-0001.obj>
-------------- next part --------------

-- 
          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                    http://barzilay.org/                   Maze is Life!

Posted on the dev mailing list.