Skip to content

Instantly share code, notes, and snippets.

@danicuki
Created November 30, 2011 01:55
Show Gist options
  • Save danicuki/1407616 to your computer and use it in GitHub Desktop.
Save danicuki/1407616 to your computer and use it in GitHub Desktop.
Polynomio em Erlang
-module(polinomio).
-include_lib("eunit/include/eunit.hrl").
-import(string, [concat/2]).
polinomio(C,E) -> [{C,E}].
soma(L,[]) -> L;
soma([],L) -> L;
soma([{C1,E}|T1], [{C2,E}|T2]) -> [{C1 + C2, E}|soma(T1,T2)];
soma([{C1,E1}|T1], [{C2,E2}|T2]) ->
if E1 > E2 -> [{C1,E1}|soma(T1,[{C2,E2}|T2])];
E2 > E1 -> [{C2,E2}|soma([{C1,E1}|T1],T2)]
end.
format_expoent(0) -> "";
format_expoent(1) -> "x";
format_expoent(E) -> concat("x^", integer_to_list(E)).
format_coef(1) -> "";
format_coef(S) -> integer_to_list(S).
to_s([]) -> "";
to_s([{C,E}]) -> concat(format_coef(C), format_expoent(E));
to_s([H|T]) -> concat(concat(to_s([H]), " + "), to_s(T)).
polinomio_test_() ->
[?_assert(to_s(polinomio(1,1)) =:= "x"),
?_assert(to_s(polinomio(2,1)) =:= "2x"),
?_assert(to_s(polinomio(2,2)) =:= "2x^2"),
?_assert(to_s(polinomio(2,0)) =:= "2")
].
to_s_test_() ->
[?_assert(to_s([{2,2}, {1,1}]) =:= "2x^2 + x")
].
polinomio_soma_test_() ->
[?_assert(to_s(soma(polinomio(1,1), polinomio(1,1))) =:= "2x"),
?_assert(to_s(soma(polinomio(1,1), polinomio(1,2))) =:= "x^2 + x"),
?_assert(to_s(soma(polinomio(1,2), polinomio(1,1))) =:= "x^2 + x"),
?_assert(to_s(soma(polinomio(1,2),soma(polinomio(1,2), polinomio(1,1)))) =:= "2x^2 + x")
].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment