Ñapalm Driven Development    Archive    About

Functional Programming Guerrilla Dictionary

The main idea of this post is to support my next posts’ explanations because I will be talking about Monads. I will be adding more terms if I find it necessary. The only purpose is being a quick terms guide for understanding next posts. Kotlin is the language used for the code snippets below. Please, notice this is not an in-depth explanation of these concepts.

Glossary of Terms

Currying: is when you break down a function that takes multiple arguments into a series of functions that take part of the arguments.

val benchmark = fun(startInMilliseconds: Int): (Int) -> Int {
    return fun(endInMilliseconds: Int): Int {
        return endInMilliseconds - startInMilliseconds
    }
}

val timeLapse = benchmark(1000)
timeLapse(5000) // result: 4000

This is also an example of a Closure.

Function Composition: to combine simple functions to build more complicated ones.

fun main(args: Array<String>) {
    val oddLength = compose(::isOdd, ::length)
    val strings = listOf("a", "ab", "abc")
    println(strings.filter(oddLength))
}

fun isOdd(x: Int) = x % 2 != 0
fun length(s: String) = s.length

fun <A, B, C> compose(f: (B) -> C, g: (A) -> B): (A) -> C {
    return { x -> f(g(x)) }
}

Inside the compose function, you can find the concept of mathematical composition, because compose is f(g(x)).

Functor: is something that can be mapped over to obtain a set of new things. For that purpose, we use .map(f) method. An array is one popular functor.

arrayListOf(1,2,3).map { it*2 }

Applicative Functor: has more structure than a functor but less than a monad. This means, an applicative knows how to apply a function wrapped in a context to a value wrapped in a context.

For making easier to understand, let’s define the apply function. This function knows how to deal with values wrapped in the same context.

infix fun <A, B> Option<(A) -> B>.apply(f: Option<A>): Option<B> =
        when (this) {
            is Option.None -> Option.None
            is Option.Some -> f.map(this.value)
        }

So now, we are able to do:

Some({ a: Int -> a + 3 }) apply Some(2)
// Result is Some(5)

Monad: is a design pattern that defines how functions, operations, inputs, and outputs can be used together to build generic types, with the following organization:

  1. Define a data type, and how values of that data type are combined.

  2. Create functions that use the data type, and compose them together into operations, following the rules defined in the first step.

Monads have the following properties:

  • It has a context with a value.

  • The value doesn’t have to exists.

  • It provides a way to get the value (usually by callback)

  • A bind function which able to pull the value out from the the monad (first argument) and put that value into another function f as argument. (f should be a function that return a monad). And the returned value of bind function should be the same type of the first argument.

  • The bind function often also named flatMap

A list of all sources used for this post.

What is a functor

Applicative functor usage

Kotlin functor applicatives and applicatives

Composing functions in Kotlin

What is a monad?

title:   'Functional Programming Guerrilla Dictionary'
url:     'http://www.napalmdrivendevelopment.xyz/functional-programming-guerrilla-dictionary.html'
author:
  name:  '@artjimlop'

This is why you should learn a functional programming language

Functional programming for Android, for iOS, in Kotlin, Swift or Javascript. Lambda expressions, monads, Erlang, Scala. Do these things ring a bell to you? You’ve probably listened or read them before. So, what’s so cool about a paradigm born in the 1950’s with the appearing of this language called Lisp?

Functional Programming features

Before talking about the benefits of functional programming, I find necessary to mention some features these languages provide us. I would like to explain this features and also charge against the “it’s too complex and it has poor readability” myth by writing examples both in Kotlin and Elixir. I’m not going to say you’re not going to struggle when learning this but, from my experience, the reason of that is simply because the change of paradigm, not because of any poor readability.

A First-class function is a function that can be stored in variables and data structures, passed as arguments to and returned from other higher-order functions

// Kotlin
val double = fun(x: Int): Int {
  return x * 2
}

# Elixir
double = fn(x) -> x * 2 end

A Higher-Order function is a function that takes functions as parameters, or returns a function.

// Kotlin
val benchmark = fun(startInMilliseconds: Int): (Int) -> Int {
    return fun(endInMilliseconds: Int): Int {
        return endInMilliseconds - startInMilliseconds
    }
}

val timeLapse = benchmark(1000)
timeLapse(5000) // result: 4000

# Elixir
benchmark = fn(start_milliseconds) ->
  fn(end_milliseconds) -> end_milliseconds - start_milliseconds
  end
end

A Pure Function should have the following qualities:

  • It should depends only on the input to produce the result, not on any hidden information or external state.

  • It shouldn’t cause any observable side effects, like modifying a parameter passed by reference or global variable/object.

// Kotlin
fun printValue(x: Int) {
  println(x)
}

# Elixir
def print_value(x), do: IO.inspect(x+1)

A Closure simply creates a scope that allows the function to access and manipulate the variables outside of its scope. Let’s try to define it again: you can store some data inside a function that’s only accessible to a specific returning function.

// Kotlin
val benchmark = fun(startInMilliseconds: Int): (Int) -> Int {
    return fun(endInMilliseconds: Int): Int {
        return endInMilliseconds - startInMilliseconds
    }
}

val timeLapse = benchmark(1000)
timeLapse(5000) // result: 4000

# Elixir
benchmark = fn(start_milliseconds) ->
  fn(end_milliseconds) -> end_milliseconds - start_milliseconds
  end
end

I will use the same example of High-Order Function again, the variable startInMilliseconds (or start_milliseconds) was enclosed and is only accessible to the returning function.

Immutable State means that you can’t change any state at all.

// Kotlin
val person = Person("John Doe")
person.name = "Not John Doe" // Fails. Val cannot be reassigned.

# Elixir
map_set = MapSet.new
foo_set = MapSet.put(map_set, "foo")  

# map_set = MapSet<[]>
# foo_set = MapSet<["foo"]>

Object-oriented Programming VS Functional Programming: fight!

High availability, concurrency, parallelism, predictability, distributed systems… have you ever listened this keywords ever? I’m pretty sure it’s the case. Usually, when talking about Functional Programming VS OOP we have this tendency to just expose the dark side of Object-oriented Programming. So, let’s try to keep more positive.

Previously, I’ve enounced a bunch of functional programming features. Immutable state may sound like a not particularly interesting feature, but plays a huge role in helping us developing our systems. Not relying on Object Oriented Programming’s mutability concept helps give us predictability. Given some input, a function is going to return us the same output whether if it’s running in one core or in a thousand cores. No process is messing around with no state. A lot of complexity is drastically reduced just because we don’t have to worry about keeping threads correctly updated and synchronized.

Functional programming languages are typically less efficient in their use of CPU and memory than imperative languages. However, such slowdowns are not universal. Programs that perform intensive numerical computations written in a functional programming language has been proven to be only slightly slower than C. Also, immutability of data can in many cases lead to execution efficiency by allowing the compiler to make assumptions that are unsafe in an imperative language.

Learning a functional programming language mainly gives you a new perspective. Keep in mind that you can use these functional features explained before in other languages. This said, I would recommend to use a functional language on a future pet project or even apply these concepts to your production code if this is possible.

title:   'This is why you should learn a functional programming language'
url:     'http://www.napalmdrivendevelopment.xyz/why-learn-functional-programming.html'
author:
  name:  '@artjimlop'

What the hell is Elixir?

I really hope this post helps you wether if you’re looking for a functional programming language to learn or just if you’ve listened something about Elixir and you’re asking yourself what is elixir language good for. I have to warn you: if you’re looking for a post about Elixir vs Scala, or about functional programming concepts, you’re in the wrong place. My only ambition is to provide info about this particular ecosystem.

“What the hell is Elixir?” A question that usually comes around whenever I’m talking about Elixir at the office so, In order to help myself and others to answer this question, I have decided to create a post about that!

First of all, because Elixir is built on top of Erlang and depends heavily on it, let’s make a brief introduction to the language:

Erlang is a development platform for building scalable and reliable systems that constantly provide service with little or no downtime conceived in the mid-1980s by Ericsson. It powers various large systems and has been doing so for more than two decades, such as the WhatsApp messaging application or the Heroku cloud and, in order to make systems work 24/7 without any downtime, it has to tackle some technical challenges: Reliability, responsiveness, scalability, and constant availability.

These challenges sound so good… how are they achieved?

Concurrency is at the heart and soul of Elixir systems. The basic concurrency primitive is called an Erlang process (not to be confused with OS processes or threads), and typical systems run thousands or even millions of such processes. This processes are managed by the BEAM (Erlang virtual machine). It uses its own schedulers to distribute the execution of processes over the available CPU cores, thus parallelizing execution as much as possible. Processes are completely isolated from each other and communicate via asynchronous messages. They share no memory, and a crash of one process doesn’t cause a crash of other processes. Moreover, you are provided with means to detect a process crash and do something about it: typically, you start a new process in place of the crashed one. Communication between processes works the same way regardless of whether these processes reside in the same BEAM instance or on two different instances on two separate, remote computers. In case you already haven’t guessed it, all these features are inherited prom Erlang!

Can we talk about Elixir now?

Elixir is an alternative language for the Erlang virtual machine that allows you to write cleaner, more compact, code that does a better job of revealing your intentions. You write programs in Elixir and run them normally in BEAM. Both Erlang and Elixir are functional languages. They rely on immutable data and functions that transform data. One of the supposed benefits of this approach is that code is divided into many small, reusable, composable functions.

You can use Erlang libraries from Elixir and vice versa. There is nothing you can do in Erlang that can’t be done in Elixir, and usually the Elixir code is as performant as its Erlang counterpart. One of the most important benefits of Elixir is the ability to radically reduce boilerplate and eliminate noise from code, which results in simpler code that is easier to write and maintain. Let’s see an example. The following snippet applies the XML to the in-memory model, process the resulting changes and, finally, persist the model.

Erlang approach:

process_xml(Model, Xml) ->
  Model1 = update(Model, Xml),
  Model2 = process_changes(Model1),
  persist(Model2).

Elixir approach:

def process_xml(model, xml) do
  model
  |> update(xml)
  |> process_changes
  |> persist
end

What you’ve just seen is called the pipeline operator. |> Takes the result of the previous expression and feeds it to the next one as the first argument. The resulting code is clean, contains no temporary variables, and reads like the prose, top to bottom, left to right.

Everything is fine? Have we found the silver bullet of software engineering?

There are no silver bullets in this world (except for the actual silver bullets that kill vampires). Usually, when I am learning about a methodology, language or paradigm I don’t find the dark spots. This is my post and I wouldn’t think it’s fair to do the same way, so I decided to make a list of all downsides.

  • Erlang is by no means the fastest platform out there. The goal of the platform isn’t to squeeze out as many requests per seconds as possible, but to keep performance predictable and within limits.

  • The ecosystem built around Erlang isn’t small, but it definitely isn’t as big as that of some other languages.

  • Elixir’s ecosystem currently isn’t as mature as Erlang’s, but you can use practically any Erlang library from Elixir.

Summary

  • Erlang is a technology for developing highly available systems that constantly provide service with little or no downtime. It has been battle tested in diverse large systems for more than two decades.

  • Elixir is a modern language that makes development for the Erlang platform much more pleasant. It helps organize code more efficiently and abstracts away boilerplate, noise, and duplication.

title:   'What the hell is Elixir?'
url:     'http://www.napalmdrivendevelopment.xyz/what-is-elixir.html'
author:
  name:  '@artjimlop'