Useful pure functional programming

I guess all programmers used to the imperative model gets stunned wondering how crazy the pure functional model is. After all, how could we do anything useful without side effects, printing to the terminal, opening a window, producing logs and variables? OMG.

I did get stunned with Haskell and because of a happy insistency I realized that the problem was in my head and not in the pure functional model.


Living for a long time in the context of an imperative world made me get used to think in a specific sequential way. I always needed to tell the computer how to do every computational step, what states to hold, what variables to update, when to return some value, etc.

On the other hand, in the pure functional world, I’m forced to think in a way to transform data. Instead of thinking on each step, now I need to think how to transform some data into another, i.e. how to extract the thing I want from the thing I have.

The classical examples to show this difference involves list manipulation.

Example #1

To calculate the sum of a list in the imperative style, you need to control the current sum state, which needs to be updated at each element.

int sum(int[] list) {
  int result = 0;
  for (int i : list)
    result += i;
  return result;

In the functional world, you need to transform a list into a single number that represents the sum of all elements, i.e. the sum of an empty list will always be zero and the sum of any other list can be extracted by adding its first value and the sum of the rest of the list.

sum [] = 0
sum (x:xs) = x + sum xs

Example #2

When we need to maintain control over two lists in the imperative world, one for input and one for output, we need to include the current index of each list in the “bag of things we need to reason about in order to avoid silly errors”.

String[] toText(int[] list) {
    String[] result = new String[list.length];
    for (int i = 0; i < list.length; ++i)
        result[i] = Integer.toString(list[i]);
    return result;

The same example in the functional world stays simple as the sum of the list, the only difference is that we transform the list using the list constructor instead of the plus operator.

toText [] = []
toText (x:xs) = show x : toText xs


The pure functional model can do many more things beyond these classical examples in a way that I consider to be pretty and with free benefits. This post is yet another try to demonstrate this. As I’m quite new to the pure functional world and have no profound knowledge of Monads, Functors, Arrows and all that stuff that looks brilliant on the hand of those who knows how to use it, I guess this post will be easy to follow, as long as you have a basic understanding of Haskell.


We’ll create a calculator in Haskell. All code shown will be pure, with no side effects, including a DSL to write tests, the test executor itself and two other test case transformations, one to write the test in text form and one to write the same text in JUnit form.

Test cases

First, let’s define the test cases’ format. They are a sequence of actions and assertions:

data TestSequence =
    Do Action TestSequence
  | Check Assertion TestSequence
  | Done

With that data definition, the test cases can be written like this:

test =
  Do a.
  Do b.
  Do c.
  Check d$

The need to write “Done” at the end of the test case bothers me. To avoid that, we can create a type synonym to open-ended tests:

type Test = TestSequence -> TestSequence

Now the tests can be written as:

test =
  Do a.
  Do b.
  Do c.
  Check d

To me, this is a valid small DSL to write our tests cases.

The only action available to our user will be to push the buttons and the only information that could be checked is the display:

data Action =
    Press Button

data Assertion =
    DisplayHasNumber Int

data Button =
  | One
  | Two
  | Three
  | Four
  | Five
  | Six
  | Seven
  | Eight
  | Nine
  | Plus
  | Minus
  | Times
  | Divide
  | Equals
  | Clear
    deriving (Show)

First test

The first step is done. We already have a DSL to write tests that type-check. Time to write our first test:

sample :: Test
sample =
    Do (Press One).
    Do (Press Plus).
    Do (Press One).
    Do (Press Equals).
    Check (DisplayHasNumber 2).

    Do (Press Clear).
    Check (DisplayHasNumber 0).

    Do (Press Two).
    Do (Press Zero).
    Check (DisplayHasNumber 20).
    Do (Press Divide).
    Do (Press Two).
    Check (DisplayHasNumber 2).
    Do (Press Equals).
    Check (DisplayHasNumber 10)

Test transformation

Note that the test case is actually a data structure, giving us the possibility to transform it. To make the transformation easier, let’s create a function that applies some generic function to each step, creating a list with the results:

unroll :: (TestSequence -> a) -> Test -> [a]
unroll f t = g (t Done)
  where g Done = [f Done]
        g v@(Do _ next) = f v : g next
        g v@(Check _ next) = f v : g next

Test case -> Text

We can transform the test case into a text:

prettyPrint :: Test -> String
prettyPrint = unlines . unroll prettyPrintTestSequence

prettyPrintTestSequence :: TestSequence -> String
prettyPrintTestSequence s =
    case s of
      Done              -> "end"
      Do action _       -> prettyPrintAction action
      Check assertion _ -> prettyPrintAssertion assertion

prettyPrintAction :: Action -> String
prettyPrintAction (Press button) = 
    "press " ++ prettyPrintButton button

prettyPrintButton :: Button -> String
prettyPrintButton = map toLower . show

prettyPrintAssertion :: Assertion -> String
prettyPrintAssertion (DisplayHasNumber number) = 
    "the display should be showing the number " ++ 
    show number

Let’s try in GHCi:

\> putStr $ prettyPrint sample
press one
press plus
press one
press equals
the display should be showing the number 2
press clear
the display should be showing the number 0
press two
press zero
the display should be showing the number 20
press divide
press two
the display should be showing the number 2
press equals
the display should be showing the number 10

Test case -> JUnit

We can translate our test case into JUnit:

generateJUnit :: Test -> String
generateJUnit = 
    ("@Test\npublic void test() {\n" ++) . 
    unlines .
    unroll generateJUnitTestSequence

generateJUnitTestSequence :: TestSequence -> String
generateJUnitTestSequence s =
    case s of
      Done      -> "}"
      Do a _    -> generateJUnitAction a
      Check a _ -> generateJUnitAssertion a

generateJUnitAction :: Action -> String
generateJUnitAction (Press b) =
    generateJUnitButton b ++ ".press();"

generateJUnitButton :: Button -> String
generateJUnitButton b = "getButton" ++ show b ++ "()"

generateJUnitAssertion :: Assertion -> String
generateJUnitAssertion (DisplayHasNumber n) =
    "assertEquals(" ++ show n ++ ", getDisplayNumber());"

At GHCi:

\> putStr $ generateJUnit sample
public void test() {
assertEquals(2, getDisplayNumber());
assertEquals(0, getDisplayNumber());
assertEquals(20, getDisplayNumber());
assertEquals(2, getDisplayNumber());
assertEquals(10, getDisplayNumber());

Concrete test

And of course, we can use our test case data structure to actually test a calculator implementation:

data TestResult =
  | Failed FailureMessage

type FailureMessage = String

instance Show TestResult where
    show Ok = "Test passed"
    show (Failed m) = "Test failed: " ++ m

checkTest :: Test -> TestResult
checkTest t = 
    (threadCheckState . unroll checkTestSequence $ t)

threadCheckState :: [State Calculator TestResult] ->
                    State Calculator TestResult 
threadCheckState = go 0
  where go _ [] = return Ok
        go n (x:xs) = x >>= (f n xs)
        f n xs Ok = go (n + 1) xs
        f n _ (Failed m) = 
          return . Failed $
            "Step " ++ show n ++ ". " ++ m

checkTestSequence :: TestSequence ->
                     State Calculator TestResult
checkTestSequence Done = return Ok
checkTestSequence (Do a _) = checkAction a
checkTestSequence (Check a _) = checkAssertion a

checkAction :: Action -> State Calculator TestResult
checkAction (Press b) = do
    modify $ pressButton b 
    return Ok

checkAssertion :: Assertion -> State Calculator TestResult
checkAssertion (DisplayHasNumber n) =
    get >>= \c ->
      if displayNumber c == n
        then return Ok
        else return . Failed $ 
          "Wrong number in display, should be " ++
          show n ++ " but was " ++ show (displayNumber c)

Calculator’s core

Finally, to type-check our tester, we need to define a first version of our calculator. Here is your opportunity to try your own. I’ve produced the following code to pass the test:

data Calculator = Calculator {
    displayNumber :: Int
  , operation :: Maybe (Int -> Int -> Int)
  , savedNumber :: Int

pressButton :: Button -> Calculator -> Calculator
pressButton b =
  case b of
    Zero    -> appendNumber 0
    One     -> appendNumber 1
    Two     -> appendNumber 2
    Three   -> appendNumber 3
    Four    -> appendNumber 4
    Five    -> appendNumber 5
    Six     -> appendNumber 6
    Seven   -> appendNumber 7
    Eight   -> appendNumber 8
    Nine    -> appendNumber 9
    Plus    -> saveOperation (+)
    Minus   -> saveOperation (-)
    Times   -> saveOperation (*)
    Divide  -> saveOperation div
    Equals  -> performOperation
    Clear   -> clear

appendNumber :: Int -> Calculator -> Calculator
appendNumber i c = 
  c { 
    displayNumber = (displayNumber c) * 10 + i 

saveOperation :: (Int -> Int -> Int) ->
                 Calculator -> Calculator
saveOperation f c = 
  c { 
    savedNumber = (displayNumber c)
  , displayNumber = 0
  , operation = Just f

performOperation :: Calculator -> Calculator
performOperation c = 
  c { 
    savedNumber = newNumber
  , displayNumber = newNumber 
  where newNumber = 
          case (operation c) of
            Nothing -> displayNumber c
            Just f  -> let a = savedNumber c
                           b = displayNumber c 
                           f a b

clear :: Calculator -> Calculator
clear = const mkCalculator

mkCalculator :: Calculator
mkCalculator = 
  Calculator { 
    displayNumber = 0
  , operation = Nothing
  , savedNumber = 0

Running the tests

Now we can run the tester against our implementation at GHCi, let’s do it:

\> checkTest sample
Test passed

This means our calculator is good enough for our use case. To assure the test case can capture an unexpected behavior, let’s introduce a bug changing the value of the multiplication on the function “appendNumber” from “10” to “100” and run the test again:

\> checkTest sample
Test failed: Step 9. Wrong number in display, should be 20 but was 200



We’ve built a basic code for a working calculator that is good enough for a simple use case. We can add new tests and keep factoring our code, TDD style. All that was made in a 100% pure way, with no dependency upon IO, state, variables or logs.

Beyond the benefit to be able to do any kind of transformation in the test cases, we can also run as many transformations and as many tests we want in parallel, because the test and the calculator are thread-safe by the simple fact that they are pure.

We did this in only 251 lines of code. How many classes or lines are needed to do the same in your favorite language?

I hope this post can enlighten you to think outside the box of the imperative world. There are many advantages in learning a pure functional language, even if you use imperative languages at work.

The code is available at GitHub:

Bringing knowledge from Haskell to Java

There are many tutorials out there about object oriented programming and test driven development (TDD). The majority uses a simple example: a calculator.

They show the power of polymorphism by building abstractions over binary operations and the value of TDD by doing an incremental test-first code base.

In this post I’ll try to extend the calculator’s example with a different problem in mind: user interaction.

The code examples given are coded in the most used O.O. language of the globe: Java.

  • Program: Calculator for terminal.
  • Requirement: Read user’s input in the format “2 + 2” and show to the user the expected result “4“.
  • Problem: How to test-first the user interaction?

As we are making a terminal application, we’ll use and System.out to interact with the user. But, we don’t want to tie the calculator’s algorithm directly to these resources, otherwise it’ll be too hard and counter-productive to create and maintain tests for this.

A very important thing that I learned with Haskell is to separate the code into pure and impure areas. A pure code area is a group of functions that depends only on its arguments and produces just one result, i.e. functions that do not modify any information and do not depend on external data. The impure part is composed of the remaining code that depends on I/O, memory read/write, databases, etc.

The Haskell language do an awesome work to assure that this separation holds in the code: its type system makes it impossible to mix pure and impure code. In common languages, like Java, there is no distinction: every piece of code has the freedom to be impure. In consequence, developers have to pay attention to every piece of code that compose the program, taking into account the current state and possible side-effects of every instruction, even from third-party closed code.

In order to set apart the “pure” and “impure” part of our calculator, first we need to be able to identify which functions belong to each part.

All functions that constitutes the calculator’s core algorithm may fit in the pure code area, after all they are just representations of mathematical functions, which are pure by definition.

In the other hand, the part that interacts with the user is impure, because it changes and depends upon information that goes beyond its reach: prints characters to the screen and read data from the keyboard.

We should keep the impure part of the code reduced and controlled as it is always the harder part to test. It should do only what it takes to the program to actually work. In our case, the impure part is just the user interaction in the following form:

  1. User types something.
  2. Program shows some text.
  3. Go back to 1.

This interaction is abstract enough to be set totally apart from the code that does the real work. For instance, the following code encapsulates the whole impure part of our calculator:

public interface Program {
  String process(String input);

public class TerminalInteraction {
  public void interact(Program program) {
    Scanner s = new Scanner(;
    while (true) {
      String input = s.nextLine();
      String output = program.process(input);

With this isolation, we just made Program to be 100% testable:

assertEquals("4", program.process("2 + 2"));
assertEquals("6", program.process("2 + 2 * 2"));

Also, our calculator’s core will only handle Strings, with no direct dependency on System. This means that we can reuse the code for other projects, maybe using it to develop two different interfaces: this, the terminal one, and in the future a graphical one.

The abstraction given as an example has one limitation: every interaction with the user is made through one input line and one output line. Can you enhance it to be possible to have multiple lines as input and output in a single interaction? If you know Haskell, you could imagine something like interact, and if you don’t: Learn You a Haskell for Great Good!