Haskell Beginner, Calling Functions by their Names

Viewed 97

Trying the 99 puzzles to learning Haskell. A quality-of-life problem that I have is that every time I test a solution, I would write a function:

mySolutionForQuestion12 :: someFunctionType

testMySolutionForQuestion12 :: IO ()
testMySolutionForQuestion12 = do
    print "testMySolution"
    print $ mySolutionForQuestion12 "myInput1"
    print $ mySolutionForQuestion12 "myInput2"
    putStr "\n"

main = do
    -- neglected code to test solutions for question 1 up to 11 --
    testMySolutionForQuestion12
    ...

    -- instead I want to do something like --
    callAllFunctionsInThisFileByNameBeginningWith "test"
    -- , so that I only have to write one line of code instead of n lines --

To be able to be as lazy as possible, I would love to have a way to make my main automatically call all functions that begin with the 4 exact characters test in my .hs file.

Is this possible in Haskell? Coming from Python, for Python a dynamic language this is self evident, but for C or C++ this would need quite a workaround (I don't actually know how to do that in these languages)

I am wondering thus how would Haskellians (if this is a word?) approach this? Is there some "best practice" in this regard?

1 Answers

Best practice is first to not test your functions by printing values to IO, but instead let a proper unit testing library do it. Apart from the dinosaur HUnit, the most established one is QuickCheck, which has its focus on automatically generating test cases using randomness (but can just as well be used for hard-coded inputs). It doesn't really address the issue you're asking about here, however there's a lot convenience tooling that has been designed for QuickCheck. I use tasty as the framework from which the tests are called; it adds useful controlling mechanisms, command-line arguments, statistics etc. but you still need to explicitly list the tests in a main routine. (Which I personally consider a good thing!)

For automatically searching the source files for tests and running them, you may have a look at doctest instead.

Related