如果您愿意,请将标题更改为更合适的名称。
我正在以面向对象程序的形式做一些东西,有一个叫做world的复合体,定义如下:
(define-struct world (var1 var2 var3 loo))其中"var“1到3是Number,表示一些实际变量,如温度、湿度等。loo是"list of objects”的缩写,对象定义如下:
(define-struct obj (id act))其中id是Integer,是对象的ID,act是另一个复合词:
(define-struct act (trigger command))其中trigger将在后面解释,而command是一个String,表示将在程序的其他部分中解析的命令。
这就是我的问题:我希望trigger是一个表达式,当世界上的一些变量以某种方式存在时,它会返回true,例如,我想让它在var1和var2具有相同的值时,发出命令"start-rain"。一段“无用”的代码看起来像这样:
(define (get-commands loo0)
(local [(define (fn-for-loo todo rsf)
(cond [(empty? todo) rsf]
[else (fn-for-obj (first todo)
(rest todo)
rsf)]))
(define (fn-for-obj obj todo rsf)
(if (true? (act-trigger (obj-act obj)))
(fn-for-loo todo (cons (act-command (obj-act obj)) rsf))
(fn-for-loo todo rsf)))]
(fn-for-loo loo0 empty)))如果很难理解,这里有一个带注释的版本:
(define (get-commands loo0) ;;-------------------------------------------------This function returns (listof String), it uses local for tail-recursion
(local [(define (fn-for-loo todo rsf) ;;------------------------------------rsf is result-so-far accumulator, it is (listof String)
(cond [(empty? todo) rsf] ;;-------------------------------------rsf returned as final output of entire function when all objects are checked
[else (fn-for-obj (first todo) ;;--------------------------if some objects are unchecked, pass objects to fn-for-obj to check the first
(rest todo)
rsf)]))
(define (fn-for-obj obj todo rsf) ;;--------------------------------receiving one object of attention, other unchecked object and result-so-far
(if (true? (act-trigger (obj-act obj))) ;;-----------------------if the trigger returns true...
(fn-for-loo todo (cons (act-command (obj-act obj)) rsf)) ;;--add current object's command to the list of commands and pass on to fn-for-loo
(fn-for-loo todo rsf)))] ;;----------------------------------if trigger returns false, pass on without modification to rsf
(fn-for-loo loo0 empty))) ;;---------------------------------------------this kick-starts the local functions我的问题是,我不知道trigger应该是什么,它必须是根据world中的变量返回Boolean的东西。当然,世界的变量可以通过词法作用域或直接引用来访问,但是在程序知道世界变量将可用之前,如何用object编写trigger的表达式呢?
我正在尝试这样的东西:
(define OBJ1 (make-obj 1
(make-act (= var1 var2) "start-rain")))但是编译器会说"var1没有定义“
https://stackoverflow.com/questions/41252755
复制相似问题