Creating Anonymous Functions
Learn what anonymous functions are and how to create them.
Introducing functions
We can think of functions as subprograms within our program; they receive an input, do some computation, and then return an output. The function body is where we write expressions to do a computation. The last expression value in the function body is the function’s output. Functions are useful for reusing expressions. Let’s start with a simple example in which we’ll build messages to say hello to Ana, John, and the world. But first, try typing this in the IEx at the end of this lesson:
iex> "Hello, Mary!"
#Output -> "Hello, Mary!"
iex> "Hello, John!"
#Output -> "Hello, John!"
iex> "Hello, World!"
#Output -> "Hello, World!"
If we want to say hello to Alice and Mike, we could copy and paste the message and replace the names. But instead, we can create a function to make it easier to say hello to anything we want. First, we need to identify the things that change in the messages. In the preceding example, we can see that the only thing that changes is the name of the person or group we want to say hello to. We can write an expression that ...