> Not to reject assertions (they would be welcome), but I think that you
> need something slightly different in a functional programming language.
> 
> Assertions in procedural languages typically define system state before
> and after a particular function gets executed.
> 
> State assertions are less appropriate to functional programming languages
> (except in the context of the content of monads but that is a separate
> issue).  As I understand it, Haskell programmers should use the type system to 
>prevent
> functions from getting called w/ operands outside their domain.
> For example, a very careful programmer would specify that division is only
> allowed on a type that has already filtered out 0 
> e.g.  
> > newType NonZero :: MakeNonZero Num
> > toNonZero:: Num -> NonZero
> > toNonZero x | x==0 = error "Shouldn't be zero"      
> >             | otherwise = MakeNonZero x

Using the type system is often entirely impractical, because
the things you want to check may not be statically checkable, at
least not within the computational language the type system provides.

Inside GHC we make extensive use of assertions.  In the example you give
we might say

        divide :: Int -> Int -> Int
        divide a b = ASSERT( b /= 0 ) a/b

The ASSERT expands to

        if not (b /= 0) then error "Assertion failed on line 27 of Foo.hs"
        else a/b

In Haskell 2 I think assertions will be standard.  (So far we have
used the C preprocessor to add them, but they should jolly well be
in the language.)

It's *very* important to be able to turn all assertion-checking off, easily.
Then programmers will write expensive assertion checks 
        ASSERT( length xs < 100 )
        ASSERT( isBalanced tree )
which they would never write if they thought these checks formed
a permanent part of their code.

In our experience assertions are quite a potent debugging tool.
Note that they can check post-conditions as well as pre-conditions:

        f x y = ASSERT( pre x y && post x y r ) r
              where
                r = ...body of f...

Simon


Reply via email to