[racket] Use `set!' or not in this scenario?

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Fri Jul 19 18:09:51 EDT 2013

There are many ways to solve this problem and you have heard about two: 

-- parameters (looks almost functional) 
-- a monad (presumably using macros and well out of reach for a true beginner)

Here are some more in order of preference: 

-- if you are willing to compute the data at the module level -- widening its scope -- do so and think of the-data as a constant 
-- If x is a small number (3 - 5), I would try to use (lexical) scope. That is, I would place f2 through fx in the scope of the-data (local to f1) 
-- if x is large (> 5), consider using a unit and invoking it locally. This is NOT a beginner question. 

All of these solutions are functional and cost nearly nothing (as is the monad solution). 

If you ever consider assigning to the-data, use the solution you proposed or Carl's, depending on precise needs. 





On Jul 19, 2013, at 12:23 PM, Ben Duan wrote:

> Scenario: A piece of data is determined in the first function `f1', but is only processed in a sub-sub-sub-… function `fx'.
> 
> One way is to use pass `the-data' as arguments from `f1' through `f2' all the way down to `fx':
> 
>     (define f1 (the-data …)
>>       (f2 the-data …)
>       …)
> 
>     (define f2 (the-data …)
>>       (f3 the-data …)
>       …)
> 
>> 
>     (define fx (the-data …)
>       … the-data …)
> 
> But in the above way, the body of `f2', `f3', `f4' and so on doesn't use `the-data'. It is only passed to the next function. And I still have to add the argument `the-data'.
> 
> Another way is to use `set!':
> 
>     (define the-data …)
> 
>     (define f1 (the-data …)
>>       (set! the-data …)
>>       (f2 …)
>       …)
> 
>     (define f2 (…)
>>       (f3 …)
>       …)
> 
>> 
>     (define fx (…)
>       … the-data …)
> 
> But in this way, the benefits of being functional are lost. For example there will be some problems writing tests for these functions.
> 
> My question is, which way is better? Or are there other ways to solve this problem?
> 
> Thanks,
> Ben
> 
> P.S. This question is not about Racket. It's just a beginner's question about how to program. Please let me know if it's not appropriate to ask this kind of questions here. Thank you.
> ____________________
>  Racket Users list:
>  http://lists.racket-lang.org/users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20130719/a0a35d53/attachment-0001.html>

Posted on the users mailing list.