[英]Function environment
我正在閱讀使用R的動手編程,他在一個例子中創建了以下函數:
setup <- function(deck){
DECK <- deck
DEAL <- function(){
card <- deck[1,]
assign("deck",deck[-1,],envir = parent.env(environment()))
card
}
SHUFFLE <- function(){
random <- sample(1:52,52)
assign("deck",DECK[random,],envir = parent.env(environment()))
}
list(deal=DEAL, shuffle=SHUFFLE)
}
cards <- setup(deck)
deal <- cards$deal
shuffle <- cards$shuffle
甲板在這里 。
當我第一次調用deal
,顯示的環境是<environment: 0x9eea314>
。 然后我開始處理函數deal()
,我發現如果我再次調用setup(deck)
,交易功能將被重置。 我這樣做, deal
的環境改變為<environment: 0xad77a60>
但是當我處理deal()
從我停止的地方繼續時,我感到驚訝。 我稱之為deal
,我看到事實上環境並沒有改變。
怎么了? 當我第一次設置交易功能時,無論多少次我調用setup(deck)
它都不會改變,或者我在其他環境中創建其他函數處理,而范圍規則無法達到?
我認為問題在於你想要看的“牌組”是在cards
內 - 對象。 在shuffle()
我們可以看到這種行為:
> deal()
face suit value
17 ten clubs 10
> str(deck)
'data.frame': 52 obs. of 3 variables:
$ face : Factor w/ 13 levels "ace","eight",..: 6 8 5 11 7 2 9 10 3 4 ...
$ suit : Factor w/ 4 levels "clubs","diamonds",..: 4 4 4 4 4 4 4 4 4 4 ...
$ value: int 13 12 11 10 9 8 7 6 5 4 ...
所以我確實看到了你的困惑。 我和你一樣,期待在牌組中看到51張牌,我期待隨機排列牌值和套牌(我們也看不到),但讓我們繼續......
> deal()
face suit value
37 three diamonds 3
> deal()
face suit value
23 four clubs 4
> str(cards)
現在讓我們嘗試找到由shuffle
和deal
函數操縱的“真正的” deck
-object,它顯然與globalenv()
中保持不變的deck
對象不同。 R函數實際上是閉包,它是代碼和封閉環境的組合。 考慮到這一點,讓我們檢查一下cards
:
> str(cards)
List of 2
$ deal :function ()
..- attr(*, "srcref")=Class 'srcref' atomic [1:8] 4 15 8 7 15 7 4 8
.. .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x7f84081d3780>
$ shuffle:function ()
..- attr(*, "srcref")=Class 'srcref' atomic [1:8] 10 18 13 7 18 7 10 13
.. .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x7f84081d3780>
現在檢查cards
內第一個功能的環境 :
> ls(env=environment(cards[[1]]))
[1] "DEAL" "deck" "DECK" "SHUFFLE"
現在看一下該環境中“deck”的價值:
str(environment(cards[[1]])$deck)
'data.frame': 49 obs. of 3 variables:
$ face : Factor w/ 13 levels "ace","eight",..: 4 1 13 7 11 13 8 2 2 3 ...
$ suit : Factor w/ 4 levels "clubs","diamonds",..: 4 1 4 1 3 3 4 3 4 1 ...
$ value: int 4 1 2 9 10 2 12 8 8 5 ...
所以我認為我們已經找到了我們應該關注的實際“平台”對象(因為它具有正確的數字和隨機排序),並且它不是在globalenv()
仍然(未更改)的那個。 此外,這兩個函數的環境是共享的:
environment(cards[[2]])
#<environment: 0x7f84081702a8>
environment(cards[[1]])
#<environment: 0x7f84081702a8>
...但是,如果在游戲過程中意外地進行了shuffle
,我認為游戲“語義”可能存在問題:
> shuffle()
> str(environment(cards[[2]])$deck)
'data.frame': 52 obs. of 3 variables:
$ face : Factor w/ 13 levels "ace","eight",..: 11 9 2 7 8 1 7 3 5 13 ...
$ suit : Factor w/ 4 levels "clubs","diamonds",..: 2 3 4 4 2 4 3 4 3 3 ...
$ value: int 10 7 8 9 12 1 9 5 11 2 ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.