Skip to content

Instantly share code, notes, and snippets.

@gorkaio
Created May 6, 2020 06:28
Show Gist options
  • Save gorkaio/1cdbcf72c9435eb5ce5d0047c03d5d6d to your computer and use it in GitHub Desktop.
Save gorkaio/1cdbcf72c9435eb5ce5d0047c03d5d6d to your computer and use it in GitHub Desktop.
-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.
@elbrujohalcon
Copy link

elbrujohalcon commented May 7, 2020

Nicely done.

Remember that snake_case is preferred over camelCase, in general. Particularly for tests, frameworks like eunit will recognize functions called …_test/0 as tests and they'll not recognize functions like perfectTest/0. 🤷

@gorkaio
Copy link
Author

gorkaio commented May 7, 2020

Thanks! Is there any recommended code style checker/fixer for Erlang?

@elbrujohalcon
Copy link

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 :trollface:) is https://hex.pm/packages/rebar3_format
(More about it on NextRoll's blog).

@gorkaio
Copy link
Author

gorkaio commented May 7, 2020

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