在 Haskell 中定义函数的 2 个或多个方程可以共享相同的 where / let 块吗?
在 Haskell 中定义函数的两个或多个方程可以共享相同的 where / let 块吗?
让我举一个人为的例子来说明这个问题。
首先,考虑以下代码作为起点:
someFunction v1 v2 v3 = difference ^ v3
where
difference = v1 - v2
到目前为止,一切都很好。 但是,想象一下我需要处理“替代情况”,如果 v3 == 99 且差值 < ,我需要返回零。 4(完全任意,但可以说这些是我的要求)。
我的第一个想法是这样做:
someFunction v1 v2 99 | difference < 4 = 0
someFunction v1 v2 v3 = difference ^ v3
where
difference = v1 - v2
但是,这行不通,因为 someFunction 的第一个方程和 someFunction 的第二个方程并不共享相同的 where 块。 在这个人为的示例中这并不是什么大问题,因为 where 块中只有一个变量(“差异”)。 但在现实世界中,可能存在大量变量,并且重复这些变量是不可接受的。
我已经知道如何通过使用守卫并且只有一个方程来解决这个问题。 问题是,有没有办法让多个方程共享相同的where / let子句? 因为似乎需要有多个具有不同模式的方程,而不是被迫只有一个方程和许多守卫。
Can 2 or more equations defining a function in Haskell share the same where / let block?
Let me present a contrived example to illustrate the question.
First, consider the following code as a starting point:
someFunction v1 v2 v3 = difference ^ v3
where
difference = v1 - v2
So far, so good. But then, imagine I need to deal with an "alternative case", where I need to return zero if v3 == 99 and difference < 4 (completely arbitrary, but let's say those are my requirements).
My first thought would be to do this:
someFunction v1 v2 99 | difference < 4 = 0
someFunction v1 v2 v3 = difference ^ v3
where
difference = v1 - v2
However, that won't work because the first equation for someFunction and the second equation for someFunction are not both sharing the same where block. This is not a big deal in this contrived example because there is only one variable in the where block ("difference"). But in a real world situation, there could be a large number of variables, and it would be unacceptable to repeat them.
I already know how to solve this by using guards and having only one equation. The question is, is there a way for multiple equations to share the same where / let clause? Because it seems desirable to have multiple equations with different patterns instead of being forced to have just one equation with many guards.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种选择是将函数提升到 where 块本身:
One option would be to lift the function into the where block itself:
我认为你不能。 也许你最好的解决方案是这样的:
I think you can't. Probably your best solution is something like: