Functional Programming in Go

29 June 2022

Or lack thereof

Today I began learning Go for work. I was relatively disappointed that it doesn’t have some basic higher order functions built into the language.

I wrote something along the following lines

package main

import (
    "fmt"
    "os"
)

func main() {
    for index, value := range os.Args {
        fmt.Printf("Argument %d:\t%s\n", index, value)  
    }
}

I thought I would have preferred to write the following

package main

import (
    "fmt"
    "os"
    "strings"
)

type Pair[T, V any] struct {
    first  T
    second V
}

func Enumerate[T any](xs []T) []Pair[int, T] {
    ys := make([]Pair[int, T], len(xs))
    for index, value := range xs {
        ys[index] = Pair[int, T]{first: index, second: value}
    }

    return ys
}

func Map[T, V any](f func(T) V, xs []T) []V {
    ys := make([]V, len(xs))
    for index, value := range xs {
        ys[index] = f(value)
    }

    return ys
}

func main() {
    fmt.Println(
        strings.Join(
            Map(
                func(values Pair[int, string]) string {
                    return fmt.Sprintf(
                        "Argument %d: %s",
                        values.first,
                        values.second,
                    )
                },
                Enumerate(os.Args),
            ),
            "\n",
        ),
    )
}

But now I’m doubting whether that’s truly what I wanted to write.