Unexpected behaviour with argument defaults

后端 未结 1 552
刺人心
刺人心 2020-12-17 00:46

I just ran into something odd, which hopefully someone here can shed some light on. Basically, when a function has an argument whose default value is the argument\'s name, s

相关标签:
1条回答
  • 2020-12-17 01:14

    Default arguments are evaluated inside the scope of the function. Your f2 is similar (almost equivalent) to the following code:

    f2 = function(y) {
        if (missing(y)) y = y
        y^2
    }
    

    This makes the scoping clearer and explains why your code doesn’t work.

    Note that this is only true for default arguments; arguments that are explicitly passed are (of course) evaluated in the scope of the caller.

    Lazy evaluation, on the other hand, has nothing to do with this: all arguments are lazily evaluated, but calling f2(y) works without complaint. To show that lazy evaluation always happens, consider this:

    f3 = function (x) {
        message("x has not been evaluated yet")
        x
    }
    
    f3(message("NOW x has been evaluated")
    

    This will print, in this order:

    x has not been evaluated yet
    NOW x has been evaluated
    
    0 讨论(0)
提交回复
热议问题