Here is my first Erlang Code:
-module(factorial).
-export([fact/1,sum/1,flatten/1,flatten1/1,flatten2/1]).
fact (0) -> 1;
fact (N) -> N* fact(N-1).
sum([]) -> 0;
sum([H|T]) -> H + sum(T).
append ([],L) -> L;
append ([H|T],L) -> [H|append(T,L)].
flatten([]) -> [];
flatten([X|L]) when is_list(X) -> append(flatten(X),flatten(L));
flatten([X|L]) -> [X|flatten(L)].
%comment
%alternatively with if
flatten1([]) -> [];
flatten1([X|L]) -> if is_list(X) -> append(flatten1(X),flatten(L));
true ->[X|flatten1(L)]
end.
%or with ++
flatten2([]) -> [];
flatten2([X|L]) when is_list(X) -> flatten2(X) ++ flatten2(L);
flatten2([X|L]) -> [X|flatten2(L)].
To run it
(1) first install Erlang with apt-get install erlang
(2) Then type erl at the command line
(3) Then compile it with c(factorial).
(4) Then try out some expressions e.g.
factorial:flatten2([[1,2],3,[4,5,6]]).
It will say:
[1,2,3,4,5,6]
-module(factorial).
-export([fact/1,sum/1,flatten/1,flatten1/1,flatten2/1]).
fact (0) -> 1;
fact (N) -> N* fact(N-1).
sum([]) -> 0;
sum([H|T]) -> H + sum(T).
append ([],L) -> L;
append ([H|T],L) -> [H|append(T,L)].
flatten([]) -> [];
flatten([X|L]) when is_list(X) -> append(flatten(X),flatten(L));
flatten([X|L]) -> [X|flatten(L)].
%comment
%alternatively with if
flatten1([]) -> [];
flatten1([X|L]) -> if is_list(X) -> append(flatten1(X),flatten(L));
true ->[X|flatten1(L)]
end.
%or with ++
flatten2([]) -> [];
flatten2([X|L]) when is_list(X) -> flatten2(X) ++ flatten2(L);
flatten2([X|L]) -> [X|flatten2(L)].
To run it
(1) first install Erlang with apt-get install erlang
(2) Then type erl at the command line
(3) Then compile it with c(factorial).
(4) Then try out some expressions e.g.
factorial:flatten2([[1,2],3,[4,5,6]]).
It will say:
[1,2,3,4,5,6]
No comments:
Post a Comment