For Programmers: Free Programming Magazines  


Home > Archive > Scheme > April 2005 > Re: newbie question, scheme idioms, functional approach to general









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: newbie question, scheme idioms, functional approach to general
Hrvoje Blazevic

2005-04-18, 8:58 am

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
Patrick

2005-04-19, 4:01 pm

Hrvoje 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
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com