Lazy Evaluation
Learn some lazy evaluation techniques.
We'll cover the following...
Introduction to lazy evaluation
Lazy evaluation is when we write a series of instructions that won’t be executed right now. Instead, they will wait for a trigger that will tell them the right moment to run. It’s like if a friend of yours is cooking a roast turkey for Christmas and gives you an instruction to remove it from the oven. You can’t take it out right away when they tell you; that would be too soon. Instead, you need to wait for that little red thing in the turkey to pop up; that’s the right moment.
Lazy operations provide alternative techniques of programming and creating efficient programs. In functional programming, higher-order functions are useful for working with lazy computation because we can pass functions that will be executed later at an appropriate moment. We’ll discuss some lazy evaluation techniques with higher-order functions, starting with delaying a function’s execution.
Delay the function call
Sometimes we want to give developers the flexibility to decide when a function will be evaluated by building a new function using the existing one. Other functional languages have currying, which is a feature that delays a function’s evaluation when we pass fewer arguments than the function requires. Elixir has partial application, a feature we can use to postpone a function’s execution by wrapping it in a new function and fixing a value to any of the function’s arguments.
While we can simulate function currying in Elixir, it is not very useful because the most important and the most often changed argument in Elixir’s functions is always the first argument. Currying requires us to pass values to the arguments in sequence. This means that the last argument is the most important because it will trigger the function call. Partial application doesn’t care which argument is the most important since we can pass a fixed value in any argument position we want; that’s why it works better in Elixir.
Let’s try partial application by building an example. Imagine we want to make a word by passing a list of positions that use a given series of letters to build words. This ...