4 ms·
> I'd expect some kind of expection in that case. Sorry, what exactly do you mean by ‘expectation’ here? > This sounds like a dangerous example of monads (sin
by bradrn 5y ago
> I'd expect some kind of expection in that case.
Sorry, what exactly do you mean by ‘expectation’ here?
> This sounds like a dangerous example of monads (since you don't know if you had a Nothing value up in the chain or a valid value that can't be representated)!
Well, this particular case is of course oversimplified. There’s plenty of ways of dealing with different kinds of errors. The easiest is to define a sum type of errors:
data DivisionError = ValueMissing | NonIntegralValue
Then redefine the function to return an ‘Either DivisionError Int’:
half x
| even x = Right (x `div` 2)
| otherwise = Left NonIntegralValue
Now chaining several calls to ‘half’ will abort at the first error.