I'm trying to figure out what is the best practice to write the Haskell equivalent of assert(0)
. I know that type safety dictates that an integer must be returned from scanList
, however I wonder if there's a better way than what I wrote. Is there any way to avoid the arbitrary number 923
that is just stuck there?
module Main (main) where
import Control.Exception (assert)
l = [
Left "1",
Left "1",
Right 1,
Right 1,
Left "9"]
scanList :: [ Either String Int ] -> Int
scanList [ ] = 0
scanList (x:xs) = case x of
Right i -> i + scanList xs
Left s ->
if read s < 8
then read s + scanList xs
else assert False $ 923
main = do
print $ scanList l
From the documentation of assert
:
If the first argument evaluates to True, then the result is the second argument. Otherwise an AssertionFailed exception is raised, containing a String with the source file and line number of the call to assert.
So instead of giving False
as first argument you could actually check your if
condition there:
scanList (x:xs) = case x of
Right i -> i + scanList xs
Left s ->
assert (read s < 8) (read s + scanList xs)