在Haskell编程时有时遇到的一个问题是有时我想将模式与值进行匹配,但是我只对有关值是否与模式匹配的真假信息感兴趣(例如,特定的数据类型构造函数) )。例如:
data Color =
RGB Int Int Int
| Greyscale Int
toHex :: Color -> String
toHex color =
if isGreyscale color then something
else somethingElse
where
isGreyscale :: Color -> Bool
isGreyscale (Greyscale _) = True
isGreyscale _ = False
我想做模式匹配而不创建不必要的辅助功能,这类似于:
toHex :: Color -> String
toHex color =
if (color ~~ (Greyscale _)) then something
else somethingElse
是否存在允许与上面的示例类似的特定语法?还是在这种情况下会派上用场的成语?
答案 0 :(得分:4)
我不相信存在(或可能存在)中缀运算符,因为模式不是值;这是语法。
您正在寻找case
表达式
toHex :: Color -> String
toHex color = case color of
Greyscale _ -> something
otherwise -> somethingElse
尽管您通常将其写为
toHex :: Color -> String
toHex (Greyscale _) = something
toHex _ = somethingElse
本质上是上面代码的替代品。
GHC中还有LambdaCase
扩展名,它使您可以编写以下内容,从而消除了不必要的变量color
。
{-# LANGUAGE LambdaCase #-}
toHex :: Color -> String
toHex = \case
Greyscale _ -> something
otherwise -> somethingElse
答案 1 :(得分:2)
您可以在函数定义中使用模式匹配来确定值:
toHex :: Color -> String
toHex (Greyscale _) = something
toHex _ = somethingElse
第一个模式匹配灰度值,而不管整数值如何,第二个子句匹配其他所有内容。如果something
和somethingElse
是需要参数详细信息的函数,则可以轻松捕获它们:
toHex :: Color -> String
toHex (Greyscale g) = something g
toHex (RGB r g b) = somethingElse r g b
答案 2 :(得分:1)
您可以使用multi-way if-expressions和模式保护符来获取几乎所需的语法:
{-# LANGUAGE MultiWayIf #-}
toHex :: Color -> String
toHex color =
if | Greyscale _ <- color -> something
| otherwise -> somethingElse