FizzyElt / functional-programming

帶你探索 functional programming
https://fizzyelt.github.io/functional-programming/
MIT License
25 stars 0 forks source link

immutable #4

Open dannypsnl opened 1 year ago

dannypsnl commented 1 year ago

假設語言中計算會停機,那麼不可變表示執行順序不會影響求值結果,舉例來說 $1 + 2 + 3$ 裡面,到底要先算 $1 + 2$ 還是 $2 + 3$ 其實無所謂。同理,不可變的計算保證 $f \ e_1 \ e_2 \ ... \ e_n$ 要先算哪個 $e_n$ 是無所謂的。

反之,可變的計算就不具有此特性:

let foo : int ref -> int =
  fun x ->
    x := !x + 1;
    !x

現在,定義成 bar : int -> int ref -> ?bar : int ref -> int -> ? 的結果可能截然不同。當然,不可變只是把條件強化到「不會不同」,並不能說可變性就一定會改變計算結果,僅是可能存在該情況。

另一個例子是 print 函數,print "hello"; print "world"print "world"; print "hello" 輸出是不同的,分別是 helloworldworldhello

FizzyElt commented 1 year ago

我先大概想個大綱