create account

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

View this thread on: hive.blogpeakd.comecency.com
· @tensor ·
$25.52
Introduction to Elixir - Recursion, Tail Calls and Comprehensions - Part Five
<center>
![intro-elixir.png](https://cdn.steemitimages.com/DQmTsYJEzEiqw2yzoAgJBFn6SqsoJHqQZWpz32oHFGDesWW/intro-elixir.png)
</center>
#### 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:
- Elixir Website: https://elixir-lang.org
- Elixir Installation Instructions: https://elixir-lang.org/install.html
- Awesome Elixir Github: https://github.com/h4cc/awesome-elixir
- Phoenix Website: https://phoenixframework.org/
- Phoenix Installation Instructions: https://hexdocs.pm/phoenix/installation.html
- Elixir Documentation: https://elixir-lang.org/docs.html
- Phoenix Documentation: https://hexdocs.pm/phoenix/Phoenix.html
- LiveView Github Repository: https://github.com/phoenixframework/phoenix_live_view

##### Sources: 
- Elixir Image: https://elixir-lang.org


#### 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. 

<center>
![recur-list.png](https://cdn.steemitimages.com/DQma98VCi83GXZijxxFc7HQJyqStPdvcLDZ9UJcRRoLLrWX/recur-list.png)
</center>

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. 

<center>
![tail-call.png](https://cdn.steemitimages.com/DQmVFttzKGNKuLVmav45riDddRy7FHbrfq66gBecGKsYiLJ/tail-call.png)
</center>

In the image above, we have two different functions called `getNumber`.  The top function `getNumber/1`contains 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.  

<center>
![for-com.png](https://cdn.steemitimages.com/DQmV6LZSFcDMt3BHxAMJdCScJvcz48RNhYsM9cjyvVGLuQG/for-com.png)
</center>

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

<iframe width="560" height="315" src="https://www.youtube.com/embed/AUZta41pqNU" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

#### Curriculum
##### Intro to Elixir
- [Introduction to Elixir - A Background and the Primitive Types - Part One](https://steemit.com/utopian-io/@tensor/introduction-to-elixir---a-background-and-the-primitive-types---part-one)
- [Introduction to Elixir - Functions, Built-in and Complex Types - Part Two](https://steemit.com/utopian-io/@tensor/introduction-to-elixir---functions-built-in-and-complex-types---part-two)
- [Introduction to Elixir - Pattern Matching and Control Flow - Part Three](https://steemit.com/utopian-io/@tensor/introduction-to-elixir---pattern-matching-and-control-flow---part-three)
- [Introduction to Elixir - Guards and Conditional Macros - Part Four](https://steemit.com/utopian-io/@tensor/introduction-to-elixir---guards-and-conditional-macros---part-four)

##### Related Phoenix Videos
>  - [Phoenix 1.3 Chat Application Tutorial](https://steemit.com/utopian-io/@tensor/intro-to-elixir-phoenix-framework-1-3-chat-application)
> - [Phoenix 1.3 Contexts and Ecto Schemas](https://steemit.com/utopian-io/@tensor/intro-to-elixir-ecto-schemas-and-phoenix-contexts)

##### GraphQL Series
> - [Phoenix 1.3 GraphQL API - Part 1](https://steemit.com/utopian-io/@tensor/intro-to-elixir-building-a-graphql-api-in-phoenix-1-3)
> - [Phoenix 1.3 GraphQL API - Part 2](https://steemit.com/utopian-io/@tensor/intro-to-elixir-graphql-mutations-and-crud)
> - [Phoenix 1.3 GraphQL API - Part 3](https://steemit.com/utopian-io/@tensor/intro-to-elixir-adding-authentication-to-a-graphql-api) 
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 63 others
properties (23)
authortensor
permlinkintroduction-to-elixir---recursion-tail-calls-and-comprehensions---part-five
categoryutopian-io
json_metadata{"tags":["utopian-io","video-tutorials","steemstem","programming","technology"],"app":"steem-plus-app"}
created2019-06-01 05:23:03
last_update2019-06-01 05:23:03
depth0
children9
last_payout2019-06-08 05:23:03
cashout_time1969-12-31 23:59:59
total_payout_value19.188 HBD
curator_payout_value6.333 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length7,525
author_reputation87,856,203,149,624
root_title"Introduction to Elixir - Recursion, Tail Calls and Comprehensions - Part Five"
beneficiaries
0.
accountsteemplus-pay
weight100
1.
accountutopian.pay
weight500
max_accepted_payout100,000.000 HBD
percent_hbd10,000
post_id85,851,985
net_rshares52,038,790,738,055
author_curate_reward""
vote details (127)
@rosatravels ·
$4.66
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](https://join.utopian.io/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](https://review.utopian.io/result/9/1-1-1-1-1-1-1-1-3-).

---- 
Need help? Chat with us on [Discord](https://discord.gg/uTyJkNm).

[[utopian-moderator]](https://join.utopian.io/)
πŸ‘  , , , , , , , , , , , , , , , , , , ,
properties (23)
authorrosatravels
permlinkpsh5sv
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["tensor"],"links":["https://join.utopian.io/guidelines","https://review.utopian.io/result/9/1-1-1-1-1-1-1-1-3-","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
created2019-06-02 14:05:24
last_update2019-06-02 14:05:24
depth1
children2
last_payout2019-06-09 14:05:24
cashout_time1969-12-31 23:59:59
total_payout_value3.564 HBD
curator_payout_value1.092 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length734
author_reputation422,827,447,688,168
root_title"Introduction to Elixir - Recursion, Tail Calls and Comprehensions - Part Five"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id85,910,483
net_rshares8,658,979,694,836
author_curate_reward""
vote details (20)
@tensor ·
Thank you @rosatravels.
properties (22)
authortensor
permlinkpshjls
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["rosatravels"],"app":"steemit/0.1"}
created2019-06-02 19:03:27
last_update2019-06-02 19:03:27
depth2
children0
last_payout2019-06-09 19:03:27
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length23
author_reputation87,856,203,149,624
root_title"Introduction to Elixir - Recursion, Tail Calls and Comprehensions - Part Five"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id85,924,866
net_rshares0
@utopian-io ·
Thank you for your review, @rosatravels! Keep up the good work!
properties (22)
authorutopian-io
permlinkre-psh5sv-20190604t211735z
categoryutopian-io
json_metadata"{"app": "beem/0.20.17"}"
created2019-06-04 21:17:36
last_update2019-06-04 21:17:36
depth2
children0
last_payout2019-06-11 21:17:36
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length63
author_reputation152,955,367,999,756
root_title"Introduction to Elixir - Recursion, Tail Calls and Comprehensions - Part Five"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id86,062,091
net_rshares0
@steem-plus ·
SteemPlus upvote
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](https://steemit.com/@steem-plus) to see the many ways in which SteemPlus can improve your Steem experience on Steemit and Busy.
properties (22)
authorsteem-plus
permlinkintroduction-to-elixir---recursion-tail-calls-and-comprehensions---part-five---vote-steemplus
categoryutopian-io
json_metadata{}
created2019-06-01 19:33:30
last_update2019-06-01 19:33:30
depth1
children0
last_payout2019-06-08 19:33:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length433
author_reputation247,952,188,232,400
root_title"Introduction to Elixir - Recursion, Tail Calls and Comprehensions - Part Five"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id85,881,050
net_rshares0
@steem-ua ·
#### 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](https://discord.gg/KpBNYGz)**
properties (22)
authorsteem-ua
permlinkre-introduction-to-elixir---recursion-tail-calls-and-comprehensions---part-five-20190602t142804z
categoryutopian-io
json_metadata"{"app": "beem/0.20.19"}"
created2019-06-02 14:28:06
last_update2019-06-02 14:28:06
depth1
children0
last_payout2019-06-09 14:28:06
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length285
author_reputation23,214,230,978,060
root_title"Introduction to Elixir - Recursion, Tail Calls and Comprehensions - Part Five"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id85,911,585
net_rshares0
@steemitboard ·
Congratulations @tensor! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

<table><tr><td><img src="https://steemitimages.com/60x70/http://steemitboard.com/@tensor/votes.png?201906020418"></td><td>You made more than 22000 upvotes. Your next target is to reach 23000 upvotes.</td></tr>
</table>

<sub>_You can view [your badges on your Steem Board](https://steemitboard.com/@tensor) and compare to others on the [Steem Ranking](http://steemitboard.com/ranking/index.php?name=tensor)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>


To support your work, I also upvoted your post!


###### [Vote for @Steemitboard as a witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1) to get one more award and increased upvotes!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-tensor-20190602t050359000z
categoryutopian-io
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2019-06-02 05:04:00
last_update2019-06-02 05:04:00
depth1
children0
last_payout2019-06-09 05:04:00
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length883
author_reputation38,975,615,169,260
root_title"Introduction to Elixir - Recursion, Tail Calls and Comprehensions - Part Five"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id85,895,931
net_rshares0
@steemitboard ·
Congratulations @tensor! You received a personal award!

<table><tr><td>https://steemitimages.com/70x70/http://steemitboard.com/@tensor/birthday2.png</td><td>Happy Birthday! - You are on the Steem blockchain for 2 years!</td></tr></table>

<sub>_You can view [your badges on your Steem Board](https://steemitboard.com/@tensor) and compare to others on the [Steem Ranking](https://steemitboard.com/ranking/index.php?name=tensor)_</sub>


###### [Vote for @Steemitboard as a witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1) to get one more award and increased upvotes!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-tensor-20190616t215457000z
categoryutopian-io
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2019-06-16 21:54:57
last_update2019-06-16 21:54:57
depth1
children0
last_payout2019-06-23 21:54:57
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length612
author_reputation38,975,615,169,260
root_title"Introduction to Elixir - Recursion, Tail Calls and Comprehensions - Part Five"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id86,740,887
net_rshares0
@steemitboard ·
<center>[![](https://steemitimages.com/175x175/http://steemitboard.com/@tensor/level.png?201912150358)](https://steemitboard.com/@tensor)
<center>@tensor, sorry to see you have less Steem Power.
Your level lowered and you are now a **Red Fish**!</center>

###### [Vote for @Steemitboard as a witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1) to get one more award and increased upvotes!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-tensor-20191215t041049000z
categoryutopian-io
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2019-12-15 04:10:48
last_update2019-12-15 04:10:48
depth1
children0
last_payout2019-12-22 04:10:48
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length433
author_reputation38,975,615,169,260
root_title"Introduction to Elixir - Recursion, Tail Calls and Comprehensions - Part Five"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id93,421,358
net_rshares0
@utopian-io ·
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](https://chrome.google.com/webstore/detail/steemplus/mjbkjgcplmaneajhcbegoffkedeankaj?hl=en) or [Steeditor](https://steeditor.app)).

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

<a href='https://steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
authorutopian-io
permlinkre-introduction-to-elixir---recursion-tail-calls-and-comprehensions---part-five-20190603t004839z
categoryutopian-io
json_metadata"{"app": "beem/0.20.17"}"
created2019-06-03 00:48:42
last_update2019-06-03 00:48:42
depth1
children0
last_payout2019-06-10 00:48:42
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length588
author_reputation152,955,367,999,756
root_title"Introduction to Elixir - Recursion, Tail Calls and Comprehensions - Part Five"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id85,940,896
net_rshares0