First Class Functions

A language comparison

Photo by Jennifer Latuperisa-Andresen on Unsplash

One common pattern to use in programming is to write functions that can be stored in variables to be passed around to other functions and called in the future. Often called blocks, procs, lambdas, and closures, I’ve decided to show the differences in some of my favorite languages I use in my everyday code.

We’re going to simply store within a variable a function that prints ‘hello’, and then call it.

Ruby

Probably the most simple and concise version I’ve used is in Ruby, since we don’t have to worry about types at all. Here I decided to use the lambda literal syntax.

my_lambda = ->(text) { puts text }my_lambda.call('hello')

Typescript

Functions are such an integral part of JavaScript but I’ve decided to show the next example in TypeScript. We use const to keep within the functional paradigm of immutability here and since const s need to be initialized in TypeScript we provide the function definition inline after the type expression.

const myFunction: (text: string) => void
= (text) => console.log(text);
myFunction(‘hello’);

Java

Java 8 brought lambdas which are definitely powerful but when defining your own types that don’t align with those built into the language, it can be a little tricky since you can’t do it inline.

@FunctionalInterface
public interface MyFunctionType {
public void call(String text);
}
MyFunctionType myFunction = (text) -> System.out.println(text);myFunction.call(“hello”);

With @FunctionalInterface , you declare an unimplemented method and you can call it whatever you want (in this case call ). Then you can use that interface’s name to type your function, and use the method name to invoke it.

Swift

This happens to be my favorite syntax 🙂. The type expression and implementation have distinct looks and there’s no repetition or clutter.

let myClosure: (String) -> Void = { text in print(text) }myClosure(“hello”)

You can use type inference here and even shorthand argument names where { text in print(text) } becomes { print($0) } .

It’s interesting to see the evolution of languages and how each one ends up adopting features from the other just as spoken languages do. Functional paradigms are easing their way into those languages that aren’t truly functional the same way object-oriented concepts began to become popular in the past.