by nnm · 4y ago · 0 comments
In R
y = c(1, 2, 3)
x = y
# now x is a copy of y
I was surprised that in python
y = [1, 2, 3]
x = y
# now x is y! What, why?
In R, I am used to the fact everything is an expression:
a = if (x > y) { 0 } else { 1 }
https://stackoverflow.com/questions/15759117/what-exactly-is...
>>> def f(x):
... x = 2
>>> x = 1
>>> f(x)
>>> x
1
One might refer to r as being referentially transparent, or immutable (I don't know if it is--I am assuming). I would refer to python as using uniform reference semantics - http://metamodular.com/common-lisp-semantics.htmlIf we capture a lambda before "x = 2", and then call it afterward, does it see an x which holds the original argument value or which holds 2?
In Lisps, this stuff is clear. Mostly. Except Common Lisp has some areas where it waffles: in some iteration constructs, implementations can bind a new variable or reuse the same one. Those choices are individually clear, though.
x = 3
def f(x): # note the name here
x = 20
f(x)
x # => 3
Similarly, using a different parameter name: def g(y):
x = y
g(20)
x # => 3
You have to explicitly mark the `x` in the function to be the global one to reference it: def h(y):
global x
x = y
h(10)
x # => 10
With a lambda it would be a closure: i = lambda y : x # throwing away y for fun
i(3) # => 10
x = 20
i("hi") # => 20Would you expect `(define f (lambda(x) x))` to have awareness about some global `x`? The only difference with Python is that the closure has access to the global scope unless the variable is locally defined and a new reference is created in the frame.
Python has lexical scoping and neither set of scoping rules is directly related to passing by reference or value.