何处条款适用于多种模式 [英] Where Clause Applied To Multiple Patterns
本文介绍了何处条款适用于多种模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有多种模式的函数。我有两个或更多共享我想要替换的表达式。现在,如果我在底部写入 where
子句,请缩进并定义一个新变量,因为我想替换它的表达式不起作用。
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ myFunction firstParam secondParam = $ b $ myFunction firstParam _ = 1 +表达式
其中expression = firstParam + secondParam
编译器消息:
不在范围内:`表达式'
不在范围内:`secondParam'
我该怎么做?
解决方案
模式匹配成案例。例如:
myFunction :: Int - > Int - > Int
myFunction a b =
(0,4) - >的情况(a,b) x
(_,b) - > x + b
其中
x = a + b
这里<$ c $在两种情况下都可以看到c> x 。
I have a function with multiple patterns. I have two or more of them which share the same expression which I want to replace. Now if I write a where
clause at the bottom, indent it and define a new variable as the expression I wanted to replace it won't work.
Example:
myFunction firstParam secondParam = expression
myFunction firstParam _ = 1 + expression
where expression = firstParam + secondParam
Compiler message:
Not in scope: `expression'
Not in scope: `secondParam'
How do I do it?
解决方案
You can factor out the pattern matches into a case. For example:
myFunction :: Int -> Int -> Int
myFunction a b = case (a, b) of
(0, 4) -> x
(_, b) -> x + b
where
x = a + b
Here x
is visible in both case branches.
这篇关于何处条款适用于多种模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文