Functional Go : Taking The Gopher to it's extremes

what if we push golang to it' functional limits

The Functional Paradigm

Functional Programming is based on simple rules that aim to make programs consistent and makes parallelism humane and easy, functions are pure they don’t mutate state , objects are immutable ,no shared state ,code is declarative , a computation is nothing but an evaluation of mathematical functions .

Let’s see an example of a function in a purely functional language :

isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome x = x == reverse x

The code above is the haskell version of the palindrome function we all implemented at some point by looping trough the list and checking … In Haskell isPalindrome takes a list of chars that derives Equality (think can be compared) and returns a bool (True or False) . The Implementation is one line :

x == reverse x

the argument is compared against the output of reverse which is a function that reverses a list .

Let’s see how we can have a similar function in Golang by starting with a recursive version of reverse:

func reverse(str string) string {
	if str == "" {
		return str
	} else {
		return reverse(str[1:]) + string(str[0]) // a string is a byte array in golang 
	}
}

Now we have a function called reverse let’s see how we can implement isPalindrome in a similar function way .

func isPalindrome (str string) {
    return str == reverse(str)
}

As you can see this way we end up with a clear consice piece of code that anyone could understand , other sweet things that go can do in a functional manner are anonymous functions , functions in golang are first class citizens so we can do something like this:

isPalindrome := func (str string) {
    return str == reverse(str)
}

isPalindrome("radar")

This is just a small view of the idea of functional golang , there’s more room for improvements for example go doesn’t have batteries included functions like map,reduce or filter a good exercice would be to implement such functions and use them .

For example data processing in golang is faster than python , therefore I can create a data pipeline to clean and organize my data much more faster than I would with golang .

Say I have a list of numerical values that I want to statistically analysis an elegant way of doing so would be to group functions and apply them to a list of these values :


type p func(int) int


func apInt(functions []p, numbers []int) []int{
	j := 0
    output := make([]int,0)
	for _,f := range functions {
		for j < len(numbers) {
			fmt.Println(f(numbers[j]))
			output = append(output,f(numbers[j]))
            j++
		}
	}
    return output
}

there you go now functions is an array of functions that can be declared like this :

	listOfFuncs := []p{a, b}

and will work on all int slice with no side effects .

I just started working on lori a Golang library that aims to offer such useful things to other developers and make functional go fun and possible .