条款适用于多种模式的地方

Bul*_*aza 4 haskell pattern-matching where-clause

我有一个多模式的功能.我有两个或多个共享相同的表达式,我想要替换它.现在如果我where在底部写一个子句,缩进它并定义一个新变量作为我想要替换它的表达式将不起作用.

例:

myFunction firstParam secondParam = expression
myFunction firstParam _ = 1 + expression
    where expression = firstParam + secondParam
Run Code Online (Sandbox Code Playgroud)

编译器消息:

Not in scope: `expression'
Not in scope: `secondParam'
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

And*_*ács 11

您可以将模式匹配分解为一个案例.例如:

myFunction :: Int -> Int -> Int
myFunction a b = case (a, b) of
  (0, 4) -> x
  (_, b) -> x + b
  where
    x = a + b
Run Code Online (Sandbox Code Playgroud)

x两个案例分支都可见.