gpt4 book ai didi

haskell - 在函数中设置变量限制并在 haskell 中返回错误

转载 作者:行者123 更新时间:2023-12-02 05:44:17 24 4
gpt4 key购买 nike

嗨,我是 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

最佳答案

一个非常简单的方法如下。这使用 guard :

fun x y
| x < -1.0 || x > 1.0 || y < 1.0 || y > 2.0 = error "Value out of range"
| otherwise = x + y

See here用于报告和处理错误的一系列越来越复杂和复杂的方法。

有时 Maybe 类型更可取,正如 ivanm 指出的那样。这是完整性的示例:

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)

关于haskell - 在函数中设置变量限制并在 haskell 中返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10492122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com