Notes week of 12 Nov

“I/O monad”

input/output is a side effect.

pure functions are not supposed to have side effects

IO is a monad to sequence side effects. It also allows us to push effects to the “edges” of our program.

putStrLn :: String -> IO ()
getLine :: IO String

Testing in Haskell

Test-driven development.

  1. Outline/sketch what you want program to do
  2. Write one or more tests for that functionality
  3. Those tests will initially fail.
  4. Write minimal code to try to pass the test(s)
  5. Go back to step 2.

Lots of languages have “unit test” frameworks/libraries. (jUnit, unittest(python), pytest, cppunit, …)

Unit tests pertain to one small piece of code – one function or one class. A lot of unit tests come down to comparing actual results with expected results.

Straightforward testing library for Haskell is HUnit.

Exercise: we want a function that can determine whether a string is a “palindrome”. Example: “racecar”

Write one or more tests first.

actual @?= expected

expected @=? actual

Property-based testing

Idea: instead of manually coming up with specific examples to use in tests, we state a general property (using code) and the test system comes up with LOTS of randomly-generated examples and checks whether the property holds (is true).

Original property-based testing tool was QuickCheck. It was developed for Haskell and Erlang by John Hughes. The idea was so compelling, many other languages started adopting it.

Let’s try an example with sorting.