Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheme: overload built-in procedures, general overloading

More specifically, can you overload the built-in Scheme procedure display?

More generally, how can you overload any procedure in Scheme?

like image 840
kud0h Avatar asked Feb 24 '26 00:02

kud0h


1 Answers

Scheme doesn't have overloading based on types a`la Java/C++, it's dynamically typed so it wouldn't make sense.

You can do a few things though:

You can overload based on the structure of the arguments:

(define overload1
    (case-lambda
        ((x y) (+ x y))
        ((x y z) (+ (- x y) z))))

This doesn't really help you though since display is only going to take one argument no matter what.

(define (overload-kinda x)
    (cond
        ((list? x) (do-list x))
        ((symbol? x) (do-sym x))
        ;etc
        ))

Which is hacky but sometimes necessary.

My usual approach is higher order functions and the case lambda

(define my-display
    (case-lambda
        ((x) (display x))
        ((x f) (display (f x)))))

Now if we need special treatment for displaying anything we pass in a function to render it.

like image 172
Daniel Gratzer Avatar answered Feb 27 '26 03:02

Daniel Gratzer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!