home *** CD-ROM | disk | FTP | other *** search
/ Big Green CD 8 / BGCD_8_Dev.iso / NEXTSTEP / UNIX / Educational / R-0.49-MI / R-0.49-I / demos / language / scoping < prev   
Encoding:
Text File  |  1996-11-24  |  1.4 KB  |  49 lines

  1. ###-*- R -*-
  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. open.account <- function(total) {
  19.  
  20.     list(
  21.         deposit = function(amount) {
  22.             if(amount <= 0)
  23.                 stop("Deposits must be positive!\n")
  24.             total <<- total + amount
  25.             cat(amount,"deposited. Your balance is", total, "\n\n")
  26.         },
  27.         withdraw = function(amount) {
  28.             if(amount > total)
  29.                 stop("You don't have that much money!\n")
  30.             total <<- total - amount
  31.             cat(amount,"withdrawn.  Your balance is", total, "\n\n")
  32.         },
  33.         balance = function() {
  34.             cat("Your balance is", total, "\n\n")
  35.         }
  36.     )
  37. }
  38.  
  39. ross <- open.account(100)
  40. robert <- open.account(200)
  41.  
  42. ross$withdraw(30)
  43. ross$balance()
  44. robert$balance()
  45.  
  46. ross$deposit(50)
  47. ross$balance()
  48. ross$withdraw(500)
  49.