O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A Quick Exercise

Let’s see how much Haskell you can understand just by first grasping an informal, hand-wavy solution and then looking at the corresponding code. It’s very much a “think in data” solution, but also probably quite different from how you’ve seen this kind of problem approached before. Without modulo division or if statements, I give you “Functional Fizz Buzz.”

The task is this: you want Fizz every three steps, and Buzz every five steps. We note that sometimes the cycles coincide. Let’s talk cycles then.

 threes = cycle ["", "", "Fizz"]
 fives = cycle ["", "", "", "", "Buzz"]

cycle is defined like this (the real library def is more efficient, but less clear):

 cycle xs = xs ++ cycle xs -- SIMPLE version of lib

So threes just ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required