在 Scheme 或 Racket 中检测函数的调用者 [英] Detecting the caller of a function in Scheme or Racket
问题描述
在 Scheme 或 Racket 中是否可以检测函数的调用者?
In Scheme or Racket is it possible to detect the caller of a function?
例如,我可以编写一个函数来测试一个列表是否是一个原子列表,如下所示:
For example, I can write a function to test if a list is a list of atoms as follows:
(define atom? (lambda (x) (and (not (pair? x)) (not (empty? x)))))
(define lat? (lambda (l)
(define latt?
(lambda (l)
(cond
((null? l) #t)
((atom? (car l)) (latt? (cdr l)))
(else #f))))
(if (null? l) #f (latt? l))))
但不是上面的,有没有像调用者"这样的函数来做这样的事情:
but instead of the above, is there a function like "called-by" to do something like this:
(define lat?
(lambda (l)
(cond
((and (null? l) (called-by "lat?")) #t)
((atom? (car l)) (lat? (cdr l)))
(else #f))))
推荐答案
通常的方法是向函数添加一些参数,或者像您一样通过内部定义进行循环.除此之外,没有可靠的方法来找出函数的调用者.
The usual way to do this is to add some argument to the function, or make a loop via an internal definition as you did. Other than that, there is no reliable way to find out the caller of a function.
但在您的情况下,似乎缺少功能 - 将其用于上述问题非常糟糕.内部助手版本没有任何问题.(它也与任何其他语言非常相似.)
But in your case, it seems like a good lack of feature -- using it for the above problem is pretty bad. There's nothing wrong with the internal helper version. (It's also quite similar to any other language.)
最后,我希望 (lat?null)
返回 #t
因为它是一个只有原子作为元素的列表.
Finally, I'd expect (lat? null)
to return #t
since it is a list that has only atoms as elements.
这篇关于在 Scheme 或 Racket 中检测函数的调用者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!