Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell equivalent of assert(0)

Tags:

assert

haskell

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
like image 752
OrenIshShalom Avatar asked Oct 15 '25 20:10

OrenIshShalom


1 Answers

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)
like image 158
Karol Samborski Avatar answered Oct 18 '25 15:10

Karol Samborski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!