Template Method Pattern. Can we do better?

Often we encounter algorithms with a certain structure that consist of individual steps that may vary for specific implementations.

To keep things clean and in order to reduce duplicate code we should refactor common parts out.

The object-oriented solution to this is the Template Method design pattern.

But there might be an alternative, better solution to this that uses higher-order functions.
Continue reading →

Parsing Roman Numerals in C# and Haskell

This is a follow-up from my last post Functional Monadic Parsers ported to C# where I showed the implementation of basic parsers from the book Programming in Haskell by Graham Hutton in C#.

When these primitives are used to compose a parser for Roman Numerals the result yet again demonstrates the amazing capabilities and elegance of functional programming. The problem of parsing Roman Numerals is not a very difficult one. But still, I find the simplicity of constructing a solution by combining primitive parsers fascinating.

Here is the implementation. It is super easy, I was able to write this in less than 15 minutes without tests first, worked the first time.
Continue reading →

Functional Monadic Parsers ported to C#

While taking the MOOC Introduction to Functional Programming by Erik Meijer on edX the current lecture greatly increased my interest in functional parsers. Functional parsers are about the essence of (functional) programming because they are about the concept of composition which is one of the core concepts of programming whatsoever.

The content of the lecture is closely related to the chapter 8 Functional Parsers of the book Programming in Haskell by Graham Hutton. It starts out with the definition of a type for a parser and a few very basic parsers.

I’m totally amazed by the simplicity, the elegance and the compositional aspect of these examples. I find it impressive how primitive but yet powerful these simple parsers are because they can easily be combined to form more complex and very capable parsers.

As an exercise, out of curiosity, and because of old habits I implemented the examples from the book in C#.

At the end of this post there will be an ultimate uber-cool parser example of a parser for arithmetic expressions.

The complete code from this post can be found here on GitHub.

Here is what I got:

Continue reading →