Created
May 6, 2020 06:28
-
-
Save gorkaio/1cdbcf72c9435eb5ce5d0047c03d5d6d to your computer and use it in GitHub Desktop.
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
-module(tail_recursion). | |
-export([fib/1,perfect/1]). | |
-export([fibTest/0,perfectTest/0]). | |
% Tail recursive fibonacci | |
fib(N) -> fib(N, 0, 1). | |
fib(0, A, _) -> A; | |
fib(N, A, B) -> fib(N-1, A+B, A). | |
fibTest() -> | |
0 = fib(0), | |
1 = fib(1), | |
1 = fib(2), | |
2 = fib(3), | |
3 = fib(4), | |
5 = fib(5), | |
8 = fib(6), | |
13 = fib(7), | |
55 = fib(10), | |
passed. | |
% Perfect numbers | |
perfect(1) -> false; | |
perfect(N) when N>1 -> perfect(N, N-1, 0). | |
perfect(N, 1, Ac) -> N == Ac + 1; | |
perfect(N, D, Ac) when N rem D == 0 -> perfect(N, D-1, Ac+D); | |
perfect(N, D, Ac) -> perfect(N, D-1, Ac). | |
perfectTest() -> | |
false = perfect(1), | |
false = perfect(2), | |
true = perfect(6), | |
false = perfect(21), | |
true = perfect(28), | |
false = perfect(42), | |
true = perfect(496), | |
false = perfect(1024), | |
true = perfect(8128), | |
passed. |
Thanks! Is there any recommended code style checker/fixer for Erlang?
Yes! https://hex.pm/packages/rebar3_lint, which is based on https://github.com/inaka/elvis
And there are formatters, too… My favorite (and I'm not biased at all ) is https://hex.pm/packages/rebar3_format
(More about it on NextRoll's blog).
I will definitely look into it, thanks again! :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nicely done.
Remember that
snake_case
is preferred overcamelCase
, in general. Particularly for tests, frameworks likeeunit
will recognize functions called…_test/0
as tests and they'll not recognize functions likeperfectTest/0
. 🤷