Coffee Making: The Functional Way!

    Coffee making is an art! And there is a guy near my home who is good at that. He runs a coffee stall where he makes nice flavors of coffee with beautiful art works on those. And recently I just dropped in to the coffee shop while returing home from my work. As he was making a cup of coffee for me by pressing some combination of buttons on a coffee machine he had, I was just wondering the way people used to make coffee a few years back. They used to do that in a very imperative way!

cup makeCoffee (cup, coffeePowder, sweetness, canAddMilk, tempDegrees, creamFlavor) {
        Add coffeePowder amount of coffee powder in to cup
        Add sweetness amount of sugar in to cup.
        if (canAddMilk is yes)
            Fill the cup with milk
        else
            Fill the cup with water
        while(temperature of mixture is less than tempDegrees) {
            Heat the contents of cup
        }
        return cup
}

So there we go. The step-by-step procedure for making a cup of coffee. However, coffee vendors nowadays make coffee by the press of a few buttons.

cupWithCoffeePowder = addCoffeePowder(cup, quantity)
cupWithSugar = addSugar(cupWithCoffeePowder, quantity)
cupWithCoffee = fillCup(cupWithSugar, choiceOfMilkOrWater)
cupWithHotCoffee = heatMixture(cupWithCoffee, temperature)

And that’s it. Each function above is equivalent to a button on the coffee vending machine which the coffee vendor pressed.

And the above two ways of coffee making are synonymous to imperative programming vs functional programming. On careful analysis we can notice that, in the former method we specify how to make a cup of coffee. And in the latter we simply say what to do, i.e. addCoffeePowder, addSugar, fillCup, heatMixture (And the internal working of each step is handled by the machine – user has to just press the buttons and wait for his coffee). Just like how the coffee machine provides us with built in buttons and abstracts out what it does behind the scenes, a functional programming language also provides us with a basic set of functions with which we could accomplish our task or use those as building blocks for creating new functions.

And now I am gonna go and make a coffee for myself – in the functional way 😉

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s