LambdaCase
一個句法擴充套件,讓你寫\case
代替\arg -> case arg of
。
請考慮以下函式定義:
dayOfTheWeek::Int -> String
dayOfTheWeek 0 = "Sunday"
dayOfTheWeek 1 = "Monday"
dayOfTheWeek 2 = "Tuesday"
dayOfTheWeek 3 = "Wednesday"
dayOfTheWeek 4 = "Thursday"
dayOfTheWeek 5 = "Friday"
dayOfTheWeek 6 = "Saturday"
如果你想避免重複函式名稱,可以編寫如下內容:
dayOfTheWeek::Int -> String
dayOfTheWeek i = case i of
0 -> "Sunday"
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
使用 LambdaCase 擴充套件,你可以將其編寫為函式表示式,而無需為引數命名:
{-# LANGUAGE LambdaCase #-}
dayOfTheWeek::Int -> String
dayOfTheWeek = \case
0 -> "Sunday"
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"