问题
Under an OO paradigm you could have something like
class BankAccount(balance: Double) {
def deposit(...)
def withdraw(...)
}
I'm wondering how you do the equivalent in the functional paradigm?
回答1:
Have each method in the BankAccount class return a new BankAccount object with the new balance. That way, the balance can be an immutable variable.
class BankAccount(balance: Double) {
def deposit(amount: Double): BankAccount
def withdraw(amount: Double): BankAccount
}
回答2:
Make the account be a series of transactions, not just a current amount:
case class Transaction(numberOfSeashells: Int)
case class Account(transactions: Iterable[Transaction])
def addNewTransaction(startingBalance: Int, t: Transaction) = startingBalance + t.numberOfSeashells
def balance(account: Account) = account.transactions.foldLeft(0)(addNewTransaction)
val acct = Account(List(Transaction(3), Transaction(-1)))
val newBalance = balance(acct)
Result:
scala> val acct = Account(List(Transaction(3), Transaction(-1)))
acct: Account = Account(List(Transaction(3), Transaction(-1)))
scala> val newBalance = balance(acct)
newBalance: Int = 2
That way you can remove invalid transactions (chargebacks, etc).
来源:https://stackoverflow.com/questions/6798193/in-scala-how-would-i-model-a-bank-account-in-a-stateless-functional-manner