在Haskell中执行断言

Max*_*xxx 0 haskell assertion

假设我有一个计算两个数字之和的函数:

computeSum :: Int -> Int -> Int
computeSum x y = x + y
Run Code Online (Sandbox Code Playgroud)

是否有任何形式的控制来自上述函数的返回值,我只想总结两个数字,其总和是非负数且必须小于10

我刚从命令式开始进行函数式编程,我们可以简单地检查函数返回值的命令式编程,例如:

if value <= 10 and value > 0:
   return value
Run Code Online (Sandbox Code Playgroud)

只是想知道在haskell中是否有类似的东西?

Wil*_*sem 7

通常,使用a Maybe来指定"可能失败"的计算,例如:

computeSum :: Int -> Int -> Maybe Int
computeSum x y | result > 0 && result <= 10 = Just result
               | otherwise = Nothing
    where result = x + y
Run Code Online (Sandbox Code Playgroud)

因此Just result,如果断言匹配,或者Nothing如果断言不满足,它将返回a .

有时Either String a用于提供错误消息,例如:

computeSum :: Int -> Int -> Either String Int
computeSum x y | result > 0 && result <= 10 = Right result
               | otherwise = Left "Result is note between 0 and 10"
    where result = x + y
Run Code Online (Sandbox Code Playgroud)

你也可以提出错误,但我个人认为这是不可取的,因为签名没有"暗示"计算可能会失败:

computeSum :: Int -> Int -> Int
computeSum x y | result > 0 && result <= 10 = result
               | otherwise = error "result is not between 0 and 10"
    where result = x + y
Run Code Online (Sandbox Code Playgroud)