A Counter the Functional Way

Photo by Steve Johnson on Unsplash

There are many ways to create a counter; one way is the object-oriented programming way:

  • First, create a class Counter.
  • Create an object counter.
  • Now, Every time you call the counter object, it gets incremented by 1.

Now, the functional programming way:

  • First, we create a function Counter.
  • Assign the function to a variable counter (a high order function).
  • Then every time you call the counter, it gets incremented by 1.
free variable: count
cell content: 4

This technique is known as a closure:

  1. It is a function (Counter) with a nested function (increment).
  2. The function returns a nested function.
  3. The nested function has access to a variable not in its scope (count, a free variable).

So what makes closure special?
Well, it is simply a function capable of storing data. This approach is much cleaner than storing values in global variables.

Bonus: (similar code in Lua):





Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How WebRTC App Development Benefits Your Business?

WebRTC App Development Benefits

Start Learning Kubernetes

How has coronavirus impacted technical interviews?

Introduction to Kotlin

Azure — Deploying Angular App With NGINX on AKS

General Manager, Manager. Asst Manager & Other — 9 Posts

Day 24/#30daysofK8s

How to get an A in CMU’s OS (15–410) class

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mansoor Aldosari

Mansoor Aldosari


More from Medium

Why is use function is the benefit? what is the benefit of it?

You say goodbye I say hellooop

Getting started with NVIDIA Omniverse KIT — handling selection

Let’s iterate together

zip lets multiple sequences to be iterated over together