首页 > 解决方案 > 中缀模式匹配

问题描述

在 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

是否有特定的语法允许类似于上面的示例?或者也许在这种情况下会派上用场的成语?

标签: haskellfunctional-programmingalgebraic-data-types

解决方案


我不相信存在(或可能存在)中缀运算符,因为模式不是值;这是语法。

你正在寻找一个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

推荐阅读