-
-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
bd4615e
commit 3b46314
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
## Here is a little example which shows a fundamental difference between | ||
> ## R and S. It is a little example from Abelson and Sussman which models | ||
> ## the way in which bank accounts work. It shows how R functions can | ||
> ## encapsulate state information. | ||
> ## | ||
> ## When invoked, "open.account" defines and returns three functions | ||
> ## in a list. Because the variable "total" exists in the environment | ||
> ## where these functions are defined they have access to its value. | ||
> ## This is even true when "open.account" has returned. The only way | ||
> ## to access the value of "total" is through the accessor functions | ||
> ## withdraw, deposit and balance. Separate accounts maintain their | ||
> ## own balances. | ||
> ## | ||
> ## This is a very nifty way of creating "closures" and a little thought | ||
> ## will show you that there are many ways of using this in statistics. | ||
> | ||
> # Copyright (C) 1997-8 The R Core Team | ||
> | ||
> open.account <- function(total) { | ||
+ | ||
+ list( | ||
+ deposit = function(amount) { | ||
+ if(amount <= 0) | ||
+ stop("Deposits must be positive!\n") | ||
+ total <<- total + amount | ||
+ cat(amount,"deposited. Your balance is", total, "\n\n") | ||
+ }, | ||
+ withdraw = function(amount) { | ||
+ if(amount > total) | ||
+ stop("You don't have that much money!\n") | ||
+ total <<- total - amount | ||
+ cat(amount,"withdrawn. Your balance is", total, "\n\n") | ||
+ }, | ||
+ balance = function() { | ||
+ cat("Your balance is", total, "\n\n") | ||
+ } | ||
+ ) | ||
+ } | ||
|
||
> ross <- open.account(100) | ||
|
||
> robert <- open.account(200) | ||
|
||
> ross$withdraw(30) | ||
30 withdrawn. Your balance is 70 | ||
|
||
|
||
> ross$balance() | ||
Your balance is 70 | ||
|
||
|
||
> robert$balance() | ||
Your balance is 200 | ||
|
||
|
||
> ross$deposit(50) | ||
50 deposited. Your balance is 120 | ||
|
||
|
||
> ross$balance() | ||
Your balance is 120 | ||
|
||
|
||
> try(ross$withdraw(500)) # no way.. | ||
Error in ross$withdraw(500) : You don't have that much money! |