[racket] Dynamically Bind Functions

From: Carl Eastlund (cce at ccs.neu.edu)
Date: Sat Dec 22 14:14:54 EST 2012

If you are working with functions in someone else's code, you are stuck
with their definition.  When you write your own functions, however, you can
always design them as wrappers around parameters.  For instance:

(define current-add-one (make-parameter add1))

(define (add-one x)
  ((current-add-one) x))

(add-one 4)

(parameterize {[current-add-one (lambda (x) (add1 (add1 x)))]}
  (add-one 4))

So now the function and the parameter are separate, but calling the
function is always nice and short.

Carl Eastlund


On Sat, Dec 22, 2012 at 4:23 AM, Cristian Esquivias <
cristian.esquivias at gmail.com> wrote:

> Is this the general practice? It looks rather cumbersome and difficult to
> plan for.
>
> Is there anything that would prevent me from having to wrap functions in
> make-parameter calls? Something like Clojure's binding special form (if
> you're familiar with it).
>
> - Cristian
> On Dec 21, 2012 6:45 PM, "David Van Horn" <dvanhorn at ccs.neu.edu> wrote:
>
>> On 12/21/12 9:41 PM, Cristian Esquivias wrote:
>>
>>> I'm trying to replace a function with another using parameterize.
>>>
>>> For example, when I try:
>>>
>>> (define (add2 n)
>>>    (add1 (add1 n)))
>>>
>>> (parameterize ([add1 (λ [n] (+ n 2))])
>>>    (add2 2))
>>>
>>> I get an error:
>>>
>>>   parameterize: contract violation
>>>    expected: parameter?
>>>    received: #<procedure:add1>
>>>
>>> How do I re-bind functions in Racket?
>>>
>>
>> You can only use parameterize with names bound to parameter values.
>> Here's an example:
>>
>> #lang racket
>> (define padd1 (make-parameter add1))
>>
>> ((padd1) 4)
>>
>> (parameterize ([padd1 (λ (n) (+ 2 n))])
>>   ((padd1) 4))
>>
>> David
>>
>>
>>
> ____________________
>   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/20121222/083ef265/attachment.html>

Posted on the users mailing list.