Skip to content

Commit

Permalink
Create Scoping.R
Browse files Browse the repository at this point in the history
  • Loading branch information
WilliamMajanja authored May 25, 2019
1 parent bd4615e commit 3b46314
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions Scoping.R
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!

0 comments on commit 3b46314

Please sign in to comment.