[plt-scheme] Is there an idiom for throwing away some values?
(I won't mention that there are closed formula for such series.)
I hate to mention this but I think this is one of those cases that
reveal the inherent weaknesses of a fixed set of looping operators in
conventional languages. Of course, in Scheme you can always fall back
on writing such things more succinctly using a plain let-loop idiom:
#lang scheme
(define (series x)
(let-values ([(f _) (for/fold ([sum 0] [factor 1])
([n (in-range 20)])
(values
(+ sum factor)
(* factor (/ x (add1 n)))))])
f))
(define (series0 x)
(let loop ([n 1][factor 1])
(if (> n 20) 0 (+ factor (loop (+ n 1) (* factor (/ x n)))))))
(= (series 10) (series0 10))
On Jul 28, 2009, at 12:09 AM, Eric Hanchrow wrote:
> Here's some code that approximates e^x:
>
> (define (series x)
> (call-with-values
> (lambda ()
> (for/fold ([sum 0]
> [factor 1])
> ([n (in-range 20)])
> (values
> (+ sum factor)
> (* factor (/ x (add1 n))))))
> (lambda (sum ignore-me)
> sum)))
>
> I'd like to be able to instead do something like
>
> (define (series x)
> (just-the-first-value
> (for/fold ([sum 0]
> [factor 1])
> ([n (in-range 20)])
> (values
> (+ sum factor)
> (* factor (/ x (add1 n)))))))
>
> ... without having to actually write "just-the-first-value" myself :)
>
> Is there an idiom that makes this simpler than what I was doing above?
> _________________________________________________
> For list-related administrative tasks:
> http://list.cs.brown.edu/mailman/listinfo/plt-scheme