redefining built-in functions?

Started by cormullion, December 07, 2006, 09:17:16 AM

Previous topic - Next topic

cormullion

I know (just about) that you can redefine built-in functions:


(constant '+ add)
 

so that + now does fp addition via add. But can you redefine built-in functions so that they call your own versions of them?



For example, if you've made a context, which has its own default function, can you make a built-in function call that function instead of its own code? You'd somehow have to get the names right...



I'm not saying this is a good idea, and I haven't got a use in mind just yet. But I was just wondering how far this 'redefine the + function to do what I say' approach could be taken.



I've got as far as defining a default function (called 'output') that basically does a 'print' operation but keeps track of what it has printed. Could that be tied to the actual 'println' name somehow? I got stuck with my experiments... :-)

Lutz

#1
Yes you could do that:
(define (fuzzy-add)
(let (sum (apply add (args)))
(mul sum (add 0.9 (div (random) 5)))))


(constant (global '+) fuzzy-add)

> (+ 1 2)
2.792231986
> (+ 1 2)
3.042992887
> (+ 1 2)
3.181443436
> (+ 1 2)
2.719832253
>


The builty-in '+' is now a 'fuzzy-add' fuzzy-fying the result up to 20% below or above . The 'global' makes it also global and it will be recognized in every context/module.



Lutz

cormullion

#2
I like it! I will have to install something like this on the computers used by my bank... :-)



And I see now that I don't have to worry about context names at all:


(define (fuzzy-add:fuzzy-add)
  (append-file "/Users/me/Desktop/fuzzylog"
     (string (date) ": " (args) "n"))
  (let (sum (apply add (args)))
    (mul sum (add 0.9 (div (random) 5)))))

(constant (global '+) fuzzy-add)

(for (i 1 20)
(println (+ 1 i)))


and all the additions are logged. Cool!



Thanks Lutz!

Lutz

#3
... you also can limit the redefinition of a built-in function to a context/module:


(context 'foo)

(define (foo:+)
  (let (sum (apply add (args)))
      (mul sum (add 0.9 (div (random) 5)))))

(define (bar) (apply + (args)))
(context MAIN)


now you could call either when in MAIN:


> > (+ 1 2 3)
6
> (foo:+ 1 2 3)
6.306726387
> (foo:bar 1 2 3)
5.950380158
>


Inside 'foo' + works as a fuzzy floating point add, but outside it works like a normal integer add.



Lutz

Lutz

#4
Quoteand all the additions are logged. Cool!


Now that is a very cool idea :)



Lutz