Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Solving expression problem using Clojure Protocols

Protocols are Clojure’s way of making the code more expressive, structured and in a way provide abstraction and polymorphism, allowing the programmers to elegantly extend the existing program to accommodate new functionalities without modifying the existing code.

What does Clojure Protocols solve? The Expression Problem.

Before solving the problem, lets see what is Expression Problem.

More explanation…

Software (Program) perform set of operations and operations operate on data which is of different data types. How do we add new operation? How do we introduce new datatype? These both are the questions that expression problem brings in.

Expression Problem 1: How do the existing operations perform on a new data type. (i.e.,) Extend existing operations support for new data types.

The merge operation works differently for different data types.

Implementation of merge function is different for each data type. Now say, there is a new data type, custom-vector and we want the merge operation to take this custom-vector as input and return the merged value, which means we will have to modify the merge function.

Expression Problem 2: Writing a new operation should operate on all the existing data types.

If we write a custom-merge function, will have to take care of all the existing data types, which can be easily solved in functional programs without modifying the existing code.

Now lets see an example solving the problem 1,

In this case we cannot use the + operation for all data types and hence will have to invoke different methods for different datatypes. Now lets write a custom-addition method, which will operate on all datatypes.

Extending the string datatype to define the addition operation.

Now we want to perform addition of maps as well with same add operation.

Lets group this into a same function,

So if we want the custom-addition to operate on a new datatype, its matter of extending the protocol custom-addition, which means no modification in the code that has implemented the custom-addition. Thus solving expression problem.

Add a comment

Related posts:

Anticipando el fracaso de OKC

La idea general es esta: los Thunder han mejorado mucho y aspiran a casi todo. ¿Es cierto? ¿Ha evolucionado tanto el equipo del trueno?

Finish Stronger Than you Started

The important thing is to be grateful for where you are right now. It does not matter how far you have come. It’s important to realize that you are here again. You showed up. Sometimes, and many…