【问题标题】:Where Clause Applied To Multiple PatternsWhere 子句适用于多种模式
【发布时间】:2015-01-15 19:17:39
【问题描述】:

我有一个具有多种模式的函数。我有两个或多个共享相同的表达式,我想替换它们。现在,如果我在底部写一个where 子句,将其缩进并定义一个新变量,因为我想替换它的表达式将不起作用。

例子:

myFunction firstParam secondParam = expression
myFunction firstParam _ = 1 + expression
    where expression = firstParam + secondParam

编译器消息:

Not in scope: `expression'
Not in scope: `secondParam'

我该怎么做?

【问题讨论】:

  • 在上面的代码中,永远不会评估第二种情况,因为第一种情况会捕获任何东西,因为firstParam,secondParam 是两个变量。你到底想达到什么目的?
  • 另外,where 表达式仅适用于第二种情况,因此您的范围内没有secondParam,而第一种情况的范围内也没有expression。跨度>
  • @chi:我随机举了一个例子来说明这个问题,所以语义并不重要

标签: haskell pattern-matching where-clause


【解决方案1】:

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

myFunction :: Int -> Int -> Int
myFunction a b = case (a, b) of
  (0, 4) -> x
  (_, b) -> x + b
  where
    x = a + b

这里x 在两个case 分支中都可见。

【讨论】:

    猜你喜欢
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 2014-08-14
    • 2013-01-06
    相关资源
    最近更新 更多