简体   繁体   English

Haskell `where` 模式匹配

[英]Haskell `where` with pattern-matching

I have such function:我有这样的功能:

eval :: Expr -> Either ArithmeticError Int
eval (Const a) = Right a
eval (Add a b) = liftM2 (+) ea eb
  where
    ea = eval a
    eb = eval b
eval (Sub a b) = liftM2 (-) ea eb
  where
    ea = eval a
    eb = eval b

I would like to rewrite this with one where usage.我想用一个where用法重写这个。 Can I do it?我可以做吗? But pattern-matching should stay in this code.但是模式匹配应该留在这段代码中。 Thanks!谢谢!

There's no general, straightforward way of matching against patterns with common variables:没有通用的、直接的方法来匹配具有公共变量的模式:

foo (Bar a b) = ...
foo (Baz a b) = ...

and then writing expressions (in where clauses or elsewhere) such that a and b correspond to both patterns simultaneously.然后编写表达式(在where子句或其他地方)使得ab同时对应于两种模式。 In Haskell, a pattern creates a new scope in which variables in the pattern are bound by that pattern, and there's no way to "combine" those bindings -- a usage of a or b will either refer to the bindings in Bar ab or Baz ab , never both.在Haskell中,一个模式创建中的模式变量是由图案结合的新的范围,而且也没有办法“结合”的绑定-的使用ab要么是指在绑定Bar abBaz ab ,从来没有。

About the best you can do is use a case statement to apply a common where clause to multiple patterns and make use of a common helper function that takes a and b as arguments and explicitly rebinds them to common names, on a pattern-by-pattern basis:关于您能做的最好的事情是使用case语句将通用where子句应用于多个模式,并使用通用辅助函数,该函数将ab作为参数,并在逐个模式上明确地将它们重新绑定到通用名称基础:

eval :: Expr -> Either ArithmeticError Int
eval e = case e of
  Const a -> Right a
  Add a b -> go (+) a b
  Sub a b -> go (-) a b

  where go op a b = liftM2 op (eval a) (eval b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM