[Haskell-cafe] "doctest" for haskell -- a good project?

Arnar Birgisson arnarbi at gmail.com
Sat Mar 22 14:58:05 EDT 2008


Hey Don,

On Sat, Mar 22, 2008 at 8:39 AM, Don Stewart <dons at galois.com> wrote:
>  I'm not sure how doctest works, or how it would work in a Haskell
>  setting, could you elaborate?

In a nutshell, Python doctest has the programmer put an example "interactive
session" in a functions docstring. A doctest module then extracts those, tries
running the function on the inputs and sees if it matches the output.
Best shown by
an example:

def adder(a,b):
    """Returns the sum of the two arguments.

    >>> adder(10,10)
    20
    >>> adder("a","b")
    'ab'
    >>> adder(10,"100")
    Traceback (most recent call last):
      File "test.py", line 6, in adder
        return a+b
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
    """
    return a+b

if __name__ == "__main__":
    import doctest
    doctest.testmod()  # Test this module



Running this script with
$ python test.py -v
gives the following output

Trying:
    adder(10,10)
Expecting:
    20
ok
Trying:
    adder("a","b")
Expecting:
    'ab'
ok
Trying:
    adder(10,"100")
Expecting:
    Traceback (most recent call last):
      File "test.py", line 6, in adder
        return a+b
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
ok
1 items had no tests:
    __main__
1 items passed all tests:
   3 tests in __main__.adder
3 tests in 2 items.
3 passed and 0 failed.
Test passed.

I.e it extracted the test cases from the sample interactive session
and compared the real results.

>  One idea that does strike me is that it would be super useful to have
>  the ability in ghci to extract the haddocks associated with a function.
>
>      > :doc map
>
>  would result in:
>
>      -- | 'map' @f xs@ is the list obtained by applying @f@ to each element
>      -- of @xs@, i.e.,
>      --
>      -- > map f [x1, x2, ..., xn] == [f x1, f x2, ..
>      -- > map f [x1, x2, ...] == [f x1, f x2, ...]
>
>  marked up in ascii.
>
>  I'm not sure if that's related to doctest, but it sure would be useful!

Python does exactly that and it is very very useful. I'd love to see
that in GHCi.

Arnar


More information about the Haskell-Cafe mailing list