Code Comments
Programming Forum and web based access to our favorite programming groups.Patrick wrote:
> If I have a function f and I want
> to construct a list which contains the
> results of repeated calls to f with
> the additional constraint that the argument
> supplied to each next call to f is based
> on the result of the previous call, what
> is the Scheme way to solve this problem?
>
> The list should eventually look something
> like this:
>
> < f(x), f(f(x)), f(f(f(x))), ... >
>
> Or in Scheme,
>
> ( (f x) (f (f x)) (f (f (f x))) ... )
>
> Procedurally, I would use a temporary
> variable to track the most recent result
> of the series of nested calls to f.
>
> while (not_done())
> {
> x = f(x)
> add_to_the_end_of_the_list(TheList, x)
> }
>
> Very simple.
>
> What is the Scheme way to build the same
> kind of list from a function, f?
>
You do not say what is not_done() supposed to test? Number of elements
created or value of x? If I assume that it is is checking x, then
something like this would do:
(define (list-maker f done?)
(define (make x)
(if (done? x)
'()
(let ((x (f x)))
(cons x (make x)))))
make)
Here, you bind f and tester predicate.
The resulting function takes x and returns the required list.
Test run would look like this:
> (define make-test (list-maker (lambda (n) (- n 1)) zero?))
> (make-test 10)
(9 8 7 6 5 4 3 2 1 0)
-- Hrvoje
Post Follow-up to this messageHrvoje Blazevic wrote: > Patrick wrote: > > > You do not say what is not_done() supposed to test? Number of elements > created or value of x? If I assume that it is is checking x, then > something like this would do: > > (define (list-maker f done?) > (define (make x) > (if (done? x) > '() > (let ((x (f x))) > (cons x (make x))))) > make) > > Here, you bind f and tester predicate. > The resulting function takes x and returns the required list. > > Test run would look like this: > > (9 8 7 6 5 4 3 2 1 0) > > -- Hrvoje Thanks to everyone for these useful ideas. They're very helpful. -- Replace Roman numerals with digits to reply by email
Post Follow-up to this messagePowered by vBulletin
Copyright 2000-2006 Jelsoft Enterprises Limited.