Created
March 29, 2016 17:34
-
-
Save bitwalker/a4035c870196ae8f628cefad7cbc83bc to your computer and use it in GitHub Desktop.
How a body recursive function expands in Elixir
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is our function definition, | |
# It is body (not tail) recursive, as it must wait for | |
# len(tail) to return before the addition can be performed | |
# on each iteration | |
def len([]), do: 0 | |
def len([head | tail]), do: 1 + len(tail) | |
# If we call len([1, 2, 3]), this is what happens | |
len([1, 2, 3]) == 1 + len([2, 3]) | |
len([2, 3]) == 1 + len([3]) | |
len([3]) == 1 + len([]) | |
len([]) == 0 | |
# Or put another way | |
len([1, 2, 3]) == 1 + len([2,3]) + len([3]) + len([]) | |
# Expanded.. | |
len([1, 2, 3]) == 1 + 1 + 1 + 0 | |
# Result.. | |
len([1, 2, 3]) == 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment