Haskell 2010 出爐

一下子沒注意,Haskell 語言的新標準 Haskell 2010 已在七月六日出爐了。和 Haskell 98 比較,Haskell 2010 的主要變革是

  1. 原為增修功能的外部函數界面 (Foreign Function Interface)
  2. 階層模組 (Hierarchical modules) 改列入正式標準,
  3. 新增 pattern guards 語法,
  4. 拿掉了 n+k patterns.

Pattern Guards

Pattern guards 早在 1997 年便由 Simon Peyton Jones 提議,後來在 GHC 中實作。GHC 使用手冊中舉的例子是這樣的:已知 lookup 的型別是 Eq a ⇒ [(a,b)] → a → Maybe b, 假設你需要用 lookup 函數查環境 env 兩次。如果任一次結果是 Nothing, 程式就傳回 fail. 如果用 case, 程式得寫成這樣:

clunky env var1 var2 =
  case lookup env var1 of
    Nothing -> fail
    Just val1 -> case lookup env var2 of
      Nothing -> fail
      Just val2 -> val1 + val2

Pattern guards 讓我們可把程式寫成較清楚簡潔的形式:

clunky env var1 var2
  | Just val1 <- lookup env var1,
    Just val2 <- lookup env var2 = val1 + val2
  | otherwise = fail

我個人覺得這確實是很好用的語法。

n+k Patterns

Miranda 時代沿襲下來的 n+k patterns 則一直充滿著爭議。下面的階層函數中,第二行左手邊便使用了一個 n+k pattern:

fact 0 = 1
fact (n + 1) = (n + 1) × fact n

Richard Bird 是 n+k pattern 的擁護者,Philip Wadler 似乎也支持。Graham Hutton 的教科書 Programming in Haskell 中用了 n+k pattern. 他們認為自然數本來就是由 0 和後繼函數 (1+) 做出的資料型別,把串列中的資料拿掉,就成了自然數。教學上,他們認為很難跟學生解釋為什麼可對串列做配對:

foldr f e [] = e
foldr f e (x : xs) = f x (foldr f e xs)

卻不能對自然數做同樣的事:

foldN f e 0 = e
foldN f e (1 + n) = f (foldN f e n)

但更多人認為 n+k pattern 語意不清,問題多多。Lennart Augustsson 發起禁用 n+ k 運動, Paul HudakStefan Kahrs 立刻響應。 Malcolm Wallace 說 "(n+k) patterns are evil", John Launchbury 說他從語言品味的觀點就討厭 (n+k) patterns. 較早版本的 Haskell 98 報告中談及語言沿革,有如下的一節:

1.4 The n+k Pattern Controversy

For technical reasons, many people feel that n+k patterns are an incongruous language design feature that should be eliminated from Haskell. On the other hand, they serve as a vehicle for teaching introductory programming, in particular recursion over natural numbers. Alternatives to n+k patterns have been explored, but are too premature to include in Haskell 98. Thus we decided to retain this feature at present but to discourage the use of n+k patterns by Haskell users --- see Section 3.17. This feature may be altered or removed in Haskell 2, and should be avoided. Implementors are encouraged to provide a mechanism for users to selectively enable or disable n+k patterns.

現在 n+k pattern 終於在 Haskell 2010 中被拿掉了。被認為是替代方案的 View Patterns 還沒進入 Haskell 2010 標準,個人也覺得實在是太重量級了些。

This entry was posted in 計算算計 and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>