/* * Bank Account */ BankAccount = { balance: 200; fun deposit(x:int){ do: balance = balance + x; }; fun withdraw(x:int){ do: balance = balance - x; ensure: balance >= 0; rescue: [ balance = x; # 引けば0になるように(考えすぎ?) retry; ]; }; }; println "<<BankAccout demo>>"; print "BankAccount balance: "; println(BankAccount balance); # => 200 BankAccount deposit(50); println "deposit(50)"; print "BankAccount balance: "; println(BankAccount balance); # => 250 BankAccount withdraw(100); println "withdraw(100)"; print "BankAccount balance: "; println(BankAccount balance); # => 150 BankAccount withdraw(200); println "withdraw(200)"; print "BankAccount balance: "; println(BankAccount balance); # => 0 /* * myAccount */ myAccount = BankAccount + {}; println "" "<<MyAccount demo>>"; myAccount balance = 100; print "myAccount balance: "; println(myAccount balance); # => 100 myAccount deposit(50); println "deposit(50)"; print "myAccount balance: "; println(myAccount balance); # => 150 print "BankAccount balance: "; println(BankAccount balance); # => 0 /* * StockAccount */ StockAccount = BankAccount + { private fun setBalance(x:int){ do: numShares = x / pricePerShare; }; fun getBalance(){ do: numShares * pricePerShare; }; public numShares: 10; pricePerShare: 30; property balance {set: setBalance; get: getBalance;}; }; println "" "<<StockAccount demo>>"; print "StockAccount numShares: "; println(StockAccount numShares); # => 10 print "StockAccount pricePerShare: "; println(StockAccount pricePerShare); # => 30 print "StockAccount balance: "; println(StockAccount balance); # => 300 StockAccount balance = 600; print "StockAccount balance: "; println(StockAccount balance); # => 600 print "StockAccount numShares: "; println(StockAccount numShares); # => 20 StockAccount deposit(60); println "deposit(60)"; print "StockAccount balance: "; println(StockAccount balance); # => 660 print "StockAccount numShares: "; println(StockAccount numShares); # => 22 StockAccount withdraw(90); println "withdraw(90)"; print "StockAccount balance: "; println(StockAccount balance); # => 570 print "StockAccount numShares: "; println(StockAccount numShares); # => 19
fun withdraw(x:int){ do: [ balance = balance - x; if(balance < 0){ true: balance = 0; }; ]; };
このページを編集 (3219 bytes)
以下の 1 ページから参照されています。 |
This page has been visited 2845 times.