Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nice examples of imperative versus functional solutions to practical problems

I am writing some lesson materials for a course that starts in a couple of weeks. I chose Clojure as a new language for students to learn. I would like to dedicate one chapter to refactoring imperative code to functional code. For this I would like to have a set of practical problems that are not far fetched by which I could show how imperative and functional solutions compare. Preferably the problems do NOT have an emphasis on math, like project Euler, but are problems that an average programmer needs to deal with on a regular basis. Who has got some good sources for this?

Partial answer: one such source is http://langref.org/. More wanted!

like image 811
Michiel Borkent Avatar asked Mar 11 '12 11:03

Michiel Borkent


2 Answers

While not really practical (because practical problems short enough to be presented in a class tend to be a little boring), programming the Game of Life is one of my favorite ways to learn a new language. As a bonus, the functional approach is quite different (and more elegant) than imperative solutions. Additionally, any sort of problem where you're manipulating sequences of data (say, analyzing a sequence of tweets for word frequency, or something) makes for cool examples.

like image 98
Isaac Avatar answered Sep 17 '22 07:09

Isaac


It's an old chestnut, but just implementing a factorial function in various different ways is quite illuminating. Another common example is a prime number generator, which can be a bit larger.

I realise both of these are maths examples, but they only require basic knowledge.

like image 27
Adrian Mouat Avatar answered Sep 19 '22 07:09

Adrian Mouat