嗨,我是haskell的新手,我正在尝试实施以下内容,我无法完全理解它
这是我想要做的基本算法,让我们说你有
--define some basic example function
fun x y = x + y
--pseudo code for what i am trying to do
x >= -1.0 || x <= 1.0 --variables x must be within this range else ERROR
y >= 1.0 || y <= 2.0 --variables y must be within this range else ERROR
Run Code Online (Sandbox Code Playgroud)
一种非常简单的方法如下.这使用了一个警卫:
fun x y
| x < -1.0 || x > 1.0 || y < 1.0 || y > 2.0 = error "Value out of range"
| otherwise = x + y
Run Code Online (Sandbox Code Playgroud)
请参阅此处了解一系列日益复杂和复杂的报告和处理错误的方法.
Maybe正如伊万姆指出的那样,有时一种类型更可取.这是完整性的一个例子:
fun' :: Float -> Float -> Maybe Float
fun' x y
| x < -1.0 || x > 1.0 || y < 1.0 || y > 2.0 = Nothing
| otherwise = Just (x + y)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
120 次 |
| 最近记录: |