[racket] Dynamically Bind Functions
My original plan was to try to do some kind of mocking and unit testing in
racket.
For example, I have a function that takes a filename and spits out a data
structure. I wanted to create some unit tests and this mock the
open-input-file function (with a open-input-string implementation).
I originally thought parameterize would allow me write the function as I
normally would (i.e., not wrap functions in make-parameter), but it sounds
like I can't. I sounds like the best way to test this function would be to
pass in a port object and pass in a string port object for testing purposes.
- Cristian
On Sat, Dec 22, 2012 at 11:14 AM, Carl Eastlund <cce at ccs.neu.edu> wrote:
> 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/01e7d919/attachment-0001.html>