Arrow 101 — Modelling a real world problem with Semigroups

1 — Intro

FP offers us many tools to create more terse and less imperative code. But besides knowing how to use then, it is also important to learn to see our problems in a mathematical way.

2 — The Problem

Let's suppose we work for a fintech called PurpleBank. It has many financial services and it is growing their number. At some point, the company decides to offer virtual credit cards for the costumers, so they can buy online in a more secure way.

2.1 — Virtual Cards and Bills as Semigroups

I'm not going to give you an explanation about what is a Semigroup. You can find some resources about it over the internet. Category Theory for Programmers and this article are some good sources, take a look and you will get it =]

virtualCard1 + virtualCard2 ≠ virtualCard2 + virtualCard1
(SemiG1 + SemiG2) + SemiG3 = SemiG1 + (SemiG2 + SemiG3)//AlsoThis is the same relation as:(1 + 2) + 3 = 1 + (2 + 3) = 6//or("Cheer's " + "from ") + "Brazil" = 
"Cheer's " + ("from " + "Brazil")
= "Cheer's from Brazil"

3— Modelling our "database"

Now we know enough to solve our problem. Before going further, let me show how I am modeling our Charge:

4 — Solving the problem

4.1 — Virtual Cards

Before deleting our old card, we need to fuse it with an existing card. We also need to guarantee that our computation only runs if both IDs passed to us are valid. So we have this logic to merge two cards and end up with only one:

4.2 — Bills

Our card got deleted and combined with another card. So, time to pay the Bill.

5 — Improving the code

Let's create an interface for our DAO with deferred computation. First, we need a Monad capable of deferring our computation (You can look here for a tutorial about Monads). Second, we need to define a return type that changes accordingly to the Monad chosen. Like this:

Software developer at GetStream.io — I love Android =]

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