Statistics
| Revision:

root / tmp / org.txm.statsengine.r.core.win32 / res / win32 / library / base / demo / scoping.R @ 2486

History | View | Annotate | Download (1.5 kB)

1

    
2
## Here is a little example which shows a fundamental difference between
3
## R and S.  It is a little example from Abelson and Sussman which models
4
## the way in which bank accounts work.	It shows how R functions can
5
## encapsulate state information.
6
##
7
## When invoked, "open.account" defines and returns three functions
8
## in a list.  Because the variable "total" exists in the environment
9
## where these functions are defined they have access to its value.
10
## This is even true when "open.account" has returned.  The only way
11
## to access the value of "total" is through the accessor functions
12
## withdraw, deposit and balance.  Separate accounts maintain their
13
## own balances.
14
##
15
## This is a very nifty way of creating "closures" and a little thought
16
## will show you that there are many ways of using this in statistics.
17

    
18
#  Copyright (C) 1997-8 The R Core Team
19

    
20
open.account <- function(total) {
21

    
22
    list(
23
	 deposit = function(amount) {
24
	     if(amount <= 0)
25
		 stop("Deposits must be positive!\n")
26
	     total <<- total + amount
27
	     cat(amount,"deposited. Your balance is", total, "\n\n")
28
	 },
29
	 withdraw = function(amount) {
30
	     if(amount > total)
31
		 stop("You don't have that much money!\n")
32
	     total <<- total - amount
33
	     cat(amount,"withdrawn.  Your balance is", total, "\n\n")
34
	 },
35
	 balance = function() {
36
	     cat("Your balance is", total, "\n\n")
37
	 }
38
	 )
39
}
40

    
41
ross <- open.account(100)
42
robert <- open.account(200)
43

    
44
ross$withdraw(30)
45
ross$balance()
46
robert$balance()
47

    
48
ross$deposit(50)
49
ross$balance()
50
try(ross$withdraw(500)) # no way..