在Haskell中的case构造中使用匹配的值

Hal*_*own 2 haskell pattern-matching

我是一个记录的数据构造函数的模式匹配,我有以下代码块:

colorFor shape = 
  case material shape of
    ColorMaterial -> material shape
    -- etc.
Run Code Online (Sandbox Code Playgroud)

问题是:这material是一个非常重要的方法,我不想在case语句中重新计算它.我知道我可以这样做:

colorFor shape = 
  let m = material shape
  in case m of
    ColorMaterial -> m
Run Code Online (Sandbox Code Playgroud)

要么

colorFor shape = 
  case material shape of
    ColorMaterial r g b -> ColorMaterial r g b
Run Code Online (Sandbox Code Playgroud)

但我不禁想到必须有一些方法来检索模式匹配中的匹配值.这也出现在函数定义中,我想在数据构造函数中匹配某些参数而不完全解包它.

仅供参考:我是Haskell的新手,如果有更好的方法可以做我正在做的事情,我会非常乐于接受建议.任何帮助非常感谢!

Tho*_*son 8

您正在寻找" 作为模式 ":

data SomeDataType = ColorMaterial Int Int Int
                  | BlandMaterial

colorFor shape = 
  case material shape of
    res@(ColorMaterial _ _ _) -> res
    -- etc.
Run Code Online (Sandbox Code Playgroud)