LCD Digits with Scala

I recently attended one of the coding dojos run by the London Scala User Group. It was great fun, and I’d recommend getting involved to anyone who’s interested in meeting other developers and learning more about scala and functional programming. After breaking into groups, we set about tackling the ‘LCD Digits’ problem from Although fairly straightforward as a programming challenge, it offers a number of ways to experiment with different functional idioms. The goal is to write a program that takes an integer, and formats this as a string composed of the ‘.’, ‘_’, “|’ and ” ” characters so that the output resembles an LCD display.

For example, given the input 1234567890, the program should return

In our solution, we started by defining a class to represent each digit as a set of three strings—representing each line of the LCD display. A case class is used here so that the productIterator function can be used to format the display’s rows as a 3-line String:

The digits 0-9 are then represented as instantiations of this class:

With the individual digits now defined, we can turn our attention to the business logic of this problem: converting arbitrary integers into LCDDisplay objects. We will look to solve this with an LCDFormatter object, whose intended behaviour we can describe with the  following test cases:

Working iteratively, we arrived at the following implementation:

The reduce function allows us to combine any number of LCDDigit objects into one, and requires us only to specify how two such objects should be combined. We do this in the merge function defined above. Note that  reduce works in a similar fashion to fold for non-empty collections, but does not need to be provided with an initial value.

We can now write a simple application to complete the exercise, using arguments passed to the program as input:

Runing the application (using sbt) confirms that it behaves as expected:


No comments yet.

Leave a Reply

Email Updates

Subscribe to this blog and receive notifications of new posts by email.


Richard Ashworth
Technical Lead at Goodlord
Experienced software engineer and technical lead. Passionate about functional programming, agile methods and domain-driven design. Check out my blog at


Read this blog in your favourite news reader:
%d bloggers like this: