方案:重载内置程序,一般重载 [英] Scheme: overload built-in procedures, general overloading
问题描述
更具体地说,你能重载内置的 Scheme 程序显示吗?
More specifically, can you overload the built-in Scheme procedure display?
更一般地说,如何在 Scheme 中重载任何过程?
More generally, how can you overload any procedure in Scheme?
推荐答案
Scheme 没有像 Java/C++ 那样基于类型的重载,它是动态类型的,所以没有意义.
Scheme doesn't have overloading based on types a`la Java/C++, it's dynamically typed so it wouldn't make sense.
你可以做一些事情:
您可以根据参数的结构进行重载:
You can overload based on the structure of the arguments:
(define overload1
(case-lambda
((x y) (+ x y))
((x y z) (+ (- x y) z))))
这并没有真正帮助你,因为 display
无论如何都只会接受一个参数.
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.
我通常的方法是高阶函数和情况 lambda
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.
这篇关于方案:重载内置程序,一般重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!