Scheme: overload built-in procedures, general overloading

浪尽此生 提交于 2019-12-24 04:06:06

问题


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

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


回答1:


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.



来源:https://stackoverflow.com/questions/15892214/scheme-overload-built-in-procedures-general-overloading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!