Maxxx
Maxxx

Reputation: 3768

Performing assertions in Haskell

Say i have a function that computes the sum between two numbers:

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

Is there any form of control over the returned value from the above function where I only want to sum up two numbers where their sum will be non negative and must be less than 10?

I just started functional programming from imperative where we can have a simple check in imperative programming of a function's return value such as:

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

Just wondering if there is something similar to that in haskell?

Upvotes: 2

Views: 889

Answers (3)

Thomas M. DuBuisson
Thomas M. DuBuisson

Reputation: 64740

Yes, Haskell has if statements:

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."

Upvotes: 4

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476493

Typically ones uses a Maybe to specify computations that "might fail", like:

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

So it will return a Just result in case the assertions are matched, or Nothing in case the assertions are not satisfied.

Sometimes Either String a is used to provide an error message, like:

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

You can also raise an error, but personally I think this is not advisable, since the signature does not "hint" that the computation might fail:

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

Upvotes: 8

AJF
AJF

Reputation: 11913

Yes, Hoogle tells us that Control.Exception provides assert :: Bool -> a -> a.

But you could just write this yourself:

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

Upvotes: 4

Related Questions