【问题标题】:Performing assertions in Haskell在 Haskell 中执行断言
【发布时间】:2018-10-14 14:42:19
【问题描述】:

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

computeSum :: Int -> Int -> Int
computeSum x y = x + y

对于上述函数的返回值,是否有任何控制形式,我只想总结两个数字,其中他们的sum 将为非负数且必须小于 10

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

if value <= 10 and value > 0:
   return value

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

【问题讨论】:

标签: haskell assertion


【解决方案1】:

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

computeSum :: Int -> Int -> Maybe Int
computeSum x y | result > 0 && result <= 10 = Just result
               | otherwise = Nothing
    where result = x + y

因此,如果断言匹配,它将返回Just result,如果断言不满足,则返回Nothing

有时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

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

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

【讨论】:

    【解决方案2】:

    是的,Hoogle 告诉我们Control.Exception 提供assert :: Bool -&gt; a -&gt; a

    但你可以自己写:

    assert :: Bool -> a -> a
    assert False _ = error "Assertion failed!"
    assert _     a = a
    

    【讨论】:

      【解决方案3】:

      是的,Haskell 有 if 语句:

      function x y =
        let r = x + y
        in if r > 0 && r <= 10
           then r
           else error "I don't know what I'm doing."
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-30
        • 1970-01-01
        相关资源
        最近更新 更多