first-class

Introduction

In computer science a programming language has first-class functions if it treats functions as first-class objects. In particular, this means that the language supports passing functions as arguments to other functions, returning them as the results of other functions, assigning them to variables or storing them in data structures.

First-class functions are an integral part of functional programming, where the use of higher-order functions is standard practice.

A simple example of a higher-order function is the function Map which takes a function and a list as its arguments and returns a list after applying the function to every element of the list.

For a programming language to support Map it has to support passing functions as an argument.

A higher-order function is, in programming, a function that takes other functions as arguments or returns another function as its result.

The main idea is that functions have the same status as other data objects. Using higher-order functions leads to abstract and compact programs, given the complexity of the computations they perform.

Example

Create the file first-class.py

def square(x): return x * x f = square(5) print(square) print(f)

python first_class.py

<function square at 0x7ff58d862040> 25

Let us change the code

def square(x): return x * x f = square print(square) print(f) print(f(5))

python first_class.py

<function square at 0x7fd877dbd040> <function square at 0x7fd877dbd040> 25

map()

Consider an example implementation of a custom map() function from the article map() in python

def square(x): return x * x def my_map(func, arg_list): result = [] for i in arg_list: result.append(func(i)) return result squares = my_map(square, [1, 2, 3, 4, 5]) print(squares)

python custom_map.py

[1, 4, 9, 16, 25]

Banner image

Returning a function

An example of returning a function

def logger(msg): def log_message(): print('Log:', msg) return log_message log_hi = logger('Hi!') log_hi()

python first_class.py

Log: Hi!

A more complex example

def html_tag(tag): def wrap_text(msg): print('<{0}>{1}</{0}>'.format(tag, msg)) return wrap_text print_h1 = html_tag('h1') print(print_h1) print_h1('Test Headline!') print_h1('Another Headline!') print_p = html_tag('p') print_p('Test Paragraph!')

python first_class.py

<function html_tag.<locals>.wrap_text at 0x7f6b97f6db80> <h1>Test Headline!</h1> <h1>Another Headline!</h1> <p>Test Paragraph!</p>

Explanations using the example print_h1:

print_h1 = html_tag('h1')

It charges the function html_tag with the h1 tag

Now everything passed to print_h1 is no longer tag but msg, because what sticks out is no longer html_tag but wrap_text

This can be seen when you run print(print_h1)

<function html_tag.<locals>.wrap_text at 0x7f6b97f6db80>

and this msg will go into the inner function wrap_text and be wrapped in the h1 tag

Article author: Andrei Olegovich