...

/

Building Programs with Functions

Building Programs with Functions

Learn how to use functions to build programs.

In functional programming, functions are the primary tools for building a program. We cannot create a useful program without writing or using functions. They receive data, complete some operations, and return a value. They are usually short and expressive.

Multiple little functions are combined to create a larger program. The complexity of building a larger application is reduced when the functions have these properties:

  • The values are immutable.
  • The function’s result is affected only by the function’s arguments.
  • The function doesn’t generate effects beyond the value it returns.

Functions that have these properties are called pure functions. A simple example, in Elixir, is a function that adds 2 to a given number:

Press + to interact
add2 = fn (n) -> n + 2 end
IO.inspect add2.(2)
# => 4

This function takes an input, processes it, and returns a value. This is the way most functions work. Some functions will be more complex, their results are unpredictable, and they are known as impure functions. We’ll look at them in chapter 8, ...