Introduction to Elixir - Recursion, Tail Calls and Comprehensions - Part Five

in #utopian-io6 years ago


intro-elixir.png

Repository: https://github.com/elixir-lang/elixir

What Will I Learn?

  • You will learn about Looping Constructs in Elixir
  • You will learn about Recusion
  • You will learn about Tail Call Recursion and how to use it
  • You will learn how to use Comprehensions in Elixir
  • You will learn about Enumerations and the Enum Module

Requirements

System Requirements:
  • Elixir v1.8 requires Erlang 20.0 or later
OS Support for Elixir and Phoenix:
  • Mac OSx
  • Unix and Linux
  • Windows
  • Raspberry Pi
  • Docker
Required Knowledge
  • Some basic Programming Knowledge
  • An Elixir installation
  • VsCode or any other Text Editor
Resources for Elixir and Phoenix:
Sources:

Difficulty

  • Beginner

Overview

In this Video Tutorial, we take a look at the basic looping structures that are used in Elixir. Looping is a very important concept in programming and because Elixir is a Functional Programming language it makes heavy use of recursion, macros and functions. Rather than having while and do...while loops all of the looping structures and patterns in Elixir make use of recursion under the hood.

Defining Functions in Terms of Themselves with Recusion

Elixir as a language makes heavy use of Collections of data. To be able to preform operations over these collections, we need some way of looping and iterating through the data structures. If, for instance, we wanted to take a list of numbers and sum them all together then we would need a method to select each number individually to add it to the overall accumulator. And because Data is immutable by default, we can't just use a basic for loop to move through the data. This is where the idea of Recursion comes into play.


recur-list.png

In the above image, we have a recursive function called sum which takes a list of numbers and sums them together until it hits the end of the list. This function uses two clauses to define the proper behavior that it needs. The top clause defines how the function will end the loop by way of pattern matching on an empty list. The second clause pulls the head off of the list and then adds it to a recursive call to the sum function on the Tail of the list. You can see how the function unwraps the data one item at a time and then adds it all together.

Making Use of Tail Call Recursion/Optimization

When a function is called in most programming languages, the function operation results in a stack push. This means that a typical Recursive function will ultimately run out of Stack space if it calls to itself too often. In Elixir we can solve this problem by making use of a concept called Tail-call Recursion. Tail-call Recursion relies on a the idea that the last line of the function will be the recursive call. By structuring the function in this way, the compiler can use jump statements instead of preforming a stack push.


tail-call.png

In the image above, we have two different functions called getNumber. The top function getNumber/1contains two clauses; one calls down to the second function getNumber/3 and the other throws an error if n is negative. The Tail call happens in the bottom clause of the getNumber/3 function. Notice how the final line in the getNumber/3 clause is a recursive call to getNumber/3. Not only is this function faster than a non-tail call function but it also can run almost indefinitely.

Using a For Loop Comprehension to Iterate through Data

Elixir features many different macros and functions that allow the user to easily iterate over a collection of data without having to explicitly write a recursive function. All of these structures use Recursion under the hood but they hide the recursion from the user. A good example of this is the for comprehension.


for-com.png

In this image we have a handful of comprehensions. These comprehensions are very useful because they not only allow us to iterate through collections of data but they also give us an ability to filter the data and cast it into another collection type. The first comprehension just takes the data and multiples it by itself each element at a time. It then returns a list of these new elements. The second comprehension takes two lists and returns a list of tuples based on the pattern at the end of the do: block. The final two comprehensions use the optional into keyword to transfer the data into a map structure. Both of these return a map where the keys are a tuple structure and the data is a single value. The final one also features a guard which filters the data.

Full Github Source Code can be found here: https://github.com/tensor-programming/intro-to-elixir/tree/tensor-programming-part-5

Video Tutorial

Curriculum

Intro to Elixir
Related Phoenix Videos
GraphQL Series
Sort:  

Hi @tensor

Thank you for another great tutorial video adding to the series on Elixir.

Again, I find your tutorial very thorough and that you leave no stones untouched. Those who are following this introductory series will be able to get started with all these detailed content.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Chat with us on Discord.

[utopian-moderator]

Thank you for your review, @rosatravels! Keep up the good work!

Hi, @tensor!

You just got a 6.81% upvote from SteemPlus!
To get higher upvotes, earn more SteemPlus Points (SPP). On your Steemit wallet, check your SPP balance and click on "How to earn SPP?" to find out all the ways to earn.
If you're not using SteemPlus yet, please check our last posts in here to see the many ways in which SteemPlus can improve your Steem experience on Steemit and Busy.

Congratulations @tensor! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You made more than 22000 upvotes. Your next target is to reach 23000 upvotes.

You can view your badges on your Steem Board and compare to others on the Steem Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Hi @tensor!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @tensor!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Congratulations @tensor! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!


@tensor, sorry to see you have less Steem Power.
Your level lowered and you are now a Red Fish!
Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Coin Marketplace

STEEM 0.20
TRX 0.25
JST 0.038
BTC 96656.73
ETH 3341.70
USDT 1.00
SBD 3.20