oper.erl

oper.erl — Erlang source code, 1 kB (1380 bytes)

Continguts del fitxer

-module (oper).
-export ([sum/1, sum/2, sum1/1, qsort/1, pythag/1, perms/1, 
 guarda/2, filtre/2, comparar/2, parell_i_senar/1, parell_i_senar2/1]).

sum(L) -> sum(L,0).

sum([], N) -> N;
sum([H|T], N) -> sum(T, H+N).

sum1([H|T]) -> H + sum1(T);
sum1([]) ->	0.

qsort ([]) -> [];
qsort ([ Pivot |T]) ->
qsort ([X || X <- T, X < Pivot ])++ [ Pivot ] ++ qsort ([X || X <- T, X >= Pivot ]).

pythag (N) ->
	[ {A,B,C} ||
		A <- lists : seq (1,N),
		B <- lists : seq (1,N),
		C <- lists : seq (1,N),
		A+B+C =< N,
		A*A+B*B =:= C*C
	].

perms([]) -> [[]];
perms(L) -> 
%		io:format("Llista  = ~p~n", [L]),
		[[H|T] || H <- L, T <- perms(L -- [H])].


guarda(X,Y) when X > Y, X > 0, Y > 0 -> X/Y;
guarda(X,Y) when X =< Y; Y =:= 0 -> 0.

filtre(P,[H|T]) ->
	case P(H) of
		true  -> [H|filtre(P, T)];
		false -> filtre(P, T)
	end;
filtre(_, []) ->
	[].

comparar(X,Y) ->
	if 
		X>Y ->	major;
		X =:= Y -> igual; 
	true -> menor
end.

parell_i_senar(L) ->
	Senar  = [X || X <- L, (X rem 2) =:= 1],
	Parell = [X || X <- L, (X rem 2) =:= 0],
	{Senar , Parell}.


parell_i_senar2([H|T], Senar, Parell) ->
	case (H rem 2) of
		0 -> parell_i_senar2(T, Senar, [H|Parell]);
		1 -> parell_i_senar2(T, [H|Senar], Parell)
	end;
parell_i_senar2([], Senar, Parell) -> {Senar , Parell}.

parell_i_senar2(L) ->	parell_i_senar2(L, [], []).