Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

r - promise already under evaluation: recursive default argument reference or earlier problems?

Here is my R code. The functions are defined as:

f <- function(x, T) {
  10 * sin(0.3 * x) * sin(1.3 * x ^ 2) + 0.001 * x ^ 3 + 0.2 * x + 80
}

g <- function(x, T, f=f) {
  exp(-f(x) / T)
}

test <- function(g=g, T=1) { 
  g(1, T)
}

The running error is:

> test()
Error in test() :
promise already under evaluation: recursive default argument reference or earlier problems?

If I substitute the definition of f in that of g, then the error goes away.

I was wondering what the error was? How to correct it if don't substitute the definition of f in that of g? Thanks!


Update:

Thanks! Two questions:

(1) if function test further takes an argument for f, will you add something like test <- function(g.=g, T=1, f..=f){ g.(1,T, f.=f..) } ? In cases with more recursions, is it a good and safe practice adding more .?

(2) if f is a non-function argument, for example g <- function(x, T, f=f){ exp(-f*x/T) } and test <- function(g.=g, T=1, f=f){ g.(1,T, f=f.) }, will using the same name for both formal and actual non-functional arguments a good and safe practice or it may cause some potential trouble?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Formal arguments of the form x=x cause this. Eliminating the two instances where they occur we get:

f <- function(x, T) {
   10 * sin(0.3 * x) * sin(1.3 * x^2) + 0.001 * x^3 + 0.2 * x + 80 
}

g <- function(x, T, f. = f) {  ## 1. note f.
   exp(-f.(x)/T) 
}

test<- function(g. = g, T = 1) {  ## 2. note g.
   g.(1,T) 
}

test()
## [1] 8.560335e-37

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...