shared data without using mutable variables

I may not have the right vocabulary for this question, but I'm looking to understand a fundamental concept of functional programming. Thank you for reading!

If you write a purely functional program that interacts with multiple consumers, how do you model shared information? Using the example of a bank account...

With mutable variables, you can do something like this:

class BankAccount {

  private var bal: Int = 0

  def balance: Int = bal

  def deposit(amount: Int) {
    bal += amount
  }

  def withdraw(amount: Int) {
    bal += amount
  }
}

So if the balance was $0 at t0 and Bob deposits 5 at t1, then Mary checks the balance at t2, she sees 5, that is she sees the effect of Bob's action.

How would you implement this with functional programming, where variable are supposed to be immutable? I can understand that with a single consumer, Bob, you can return a new instance of BankAccount with a balance of 5. But with a second consumer, Mary, how would she access this new BankAccount?

Conceptually, one can think about balance not as a state that changes over time, but rather there is an immutable balance_t0 = 0 and an immutable balance_t1 = 5. But to do this, you would still need some way to name the balance at each point in time in your programming language...

链接地址: http://www.djcxy.com/p/80852.html

上一篇: 我为什么要学习haskell?

下一篇: 共享数据而不使用可变变量