如何在函数中分配引用单元格,然后以 sml 为单位返回值



所以我在 sml 中有一个函数,它接受一个整数值并引用它。如何为可变余额分配新值,然后返回该余额?在存款和提款模式中?

datatype Message = GetBalance | Deposit of int | WithDraw of int;
fun opening_account init_amt = let val balance = ref init_amt
                in fn GetBalance => !balance
                 | Deposit x => balance = !balance + x
                 | WithDraw x => balance = !balance - x
               end; 

要更新引用单元格,请使用 := . 即:

balance := !balance + x

如果您希望同时更新余额,然后返回新值,只需使用 ; 一个接一个地执行:

(balance := !balance + x; !balance)

相关内容

最新更新