l******9 发帖数: 579 | 1 I need to do pass by reference in R by R studio on win 7.
My code:
myfunc<-function(myhash.arg, b)
{
myhash <- myhash.arg
if (!has.key("first", myhash))
myhash["first"] <- list()
alist <- myhash["first"]
alist <- append(alist, i)
eval.parent(substitute(myhash.arg<-myhash))
return(0)
}
ahash<-hash()
for(i in 1:5)
{
myfunc(myhash.arg = ahash, b = i)
print(c("length of ahash is ", length(ahash)))
print(c("length of ahash list is ", length(ahash["first"])))
}
but, the list size is always 1, the appended elements are missed.
Any help would be appreciated. | i*******r 发帖数: 51 | 2 You can pass the env handle to a function ,and change whatever you want.
However this will cause side effects in your program, and not be recommended.
【在 l******9 的大作中提到】 : I need to do pass by reference in R by R studio on win 7. : My code: : myfunc<-function(myhash.arg, b) : { : myhash <- myhash.arg : if (!has.key("first", myhash)) : myhash["first"] <- list() : alist <- myhash["first"] : alist <- append(alist, i) : eval.parent(substitute(myhash.arg<-myhash))
| l******9 发帖数: 579 | 3 Could you please show me an example ?
what side effects ?
thanks
recommended.
【在 i*******r 的大作中提到】 : You can pass the env handle to a function ,and change whatever you want. : However this will cause side effects in your program, and not be recommended.
| i*******r 发帖数: 51 | 4 > env=environment();
> library(hash)
hash-2.2.6 provided by Decision Patterns
> hh=hash();
> has.key("a",hh)
a
FALSE
> myfun<-function(hhname,env){hh=env[[hhname]];if(!has.key("a",hh)){hh["a"]=
list()}else{append(hh["a"],1)}}
> myfun("hh",env)
> hh
containing 1 key-value pair(s).
a :
> myfun("hh",env)
[[1]]
containing 1 key-value pair(s).
a :
[[2]]
[1] 1
【在 l******9 的大作中提到】 : Could you please show me an example ? : what side effects ? : thanks : : recommended.
| i*******r 发帖数: 51 | 5 Side effects means a function changed a value in its environment.
In functional programming language, (R is not pure fp, but designed with
lots of fp ideas), the side effects are considered as a problem, since
the function call does extra things more than compute the return value from
its inputs.
【在 l******9 的大作中提到】 : Could you please show me an example ? : what side effects ? : thanks : : recommended.
|
|