Created
September 21, 2015 17:21
-
-
Save gtcarlos/7f475b07a70f0cd2214a to your computer and use it in GitHub Desktop.
Guard clauses vs If
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
defmodule GuardIf do | |
def if_double(0), do: [0] | |
def if_double(n) do | |
if rem(n, 2) == 0 do | |
if_double(n - 1) ++ [n] | |
else | |
if_double(n - 1) | |
end | |
end | |
def guard_double(0), do: [0] | |
def guard_double(n) when rem(n, 2) == 0 do | |
guard_double(n - 1) ++ [n] | |
end | |
def guard_double(n) do | |
guard_double(n - 1) | |
end | |
end | |
GuardIf.if_double(20) | |
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] | |
GuardIf.guard_double(20) | |
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment