看板 PLT 關於我們 聯絡資訊
※ 引述《etwas (i'm only dust)》之銘言: : data DataInt = D Int : deriving (Eq, Ord, Show) : newtype NewtypeInt = N Int : deriving (Eq, Ord, Show) : ===== : ghci> case undefined of D _ -> 1 : *** Exception: Prelude.undefined : the author wrote: : "the unprotected undefined is evaluated when the pattern match occurs". : i realise that matching is based on value constructors. : but under what circumstances does it have to evaluate them? 大致上,如果一個值去 match 一個 data constructor 的時候 就必須被 evaluate 成 weak head normal form (WHNF). 在這個 例子中,undefined 要和 D _ 配對,於是電腦試著把 undefined evalulate 成 WHNF,但當然做不到。於是就開始 loop 了。 : in this case, does pattern matching run into a divergence? 是的。通常 divergence 指的是無法「聚合」成一個值。 : pattern matching, does it happen in runtime, compile time or both? 在 Haskell 中應該是只有 runtime 才會發生的。 : if it's a runtime process, then some sort of bookkeeping data about : constructors should be retained during programme execution, right? 是的。基本上 runtime 時的值都有某些方式讓我們可測出它 是什麼東西。例如一個 list, 我們當然得知道它是或不是空 的 (是 [] 或是 _:_ ). : ghci> case undefined of N _ -> 1 : 1 NewtypeInt 是用 newtype 定義的, 因此和 DataInt 有些不同。 如果我們宣告 newtype T = C U, 定出的 T 其實「就是」U. newtype 的使用時機是我們想把某些 U 當作不一樣的 type (例如定義成某些 class 的 instance),但不想要多耗費一個 data constructor 去包它。 所以 NewtypeInt 的那個 N 其實是不存在的。去 match N _ 和 match _ 其實是一樣的事情。因此上面的式子不會 loop. : but something like : ghci> case 10.77 of N _ -> 1 : ghci> case "a string" of N _ -> 1 : justifiably fail : regarding to the author's explanation, why the two cases fail while : the "undefined" case succeeds? 以上這兩個情形都會出現 type error. 那又是另一個層次的問題了... :) -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.136.48.247