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"