====== Erlang - Lista 2. ======
===== Zadanie 1. (dude) =====
#!/usr/bin/env escript
main(Y) ->
X = toint(Y),
case length(X) of
0 -> io:format("usage: ./seq n [n [n]]~n");
1 -> [A] = X,
seq(A);
2 -> [A, B] = X,
seq(A, B);
3 -> [A, B, C] = X,
seq(A, B, C)
end.
toint([]) -> [];
toint([H|T]) -> [list_to_integer(H) | toint(T)].
seq(End) -> seq(1, End, 1).
seq(Start, End) -> seq(Start, End, 1).
seq(Cur, End, Step) -> if
Cur > End -> done;
Cur =< End -> io:format("~B~n", [Cur]),
seq(Cur+Step, End, Step)
end.
===== Zadanie 2. (dude) =====
-module(zad2).
-export([isum/1, imax/1]).
isum([]) -> 0;
isum([H|T]) when is_integer(H) -> H + isum(T);
isum([H|_]) -> io:format("~p is not an integer~n", [H]).
imax([]) -> 0;
imax([H|T]) when is_integer(H) -> Y = imax(T),
if
H > Y -> H;
H =< Y -> Y
end;
imax([H|_]) -> io:format("~p is not an integer~n", [H]).
===== Zadanie 3. =====
==== Wersja 1 (Ponton) ====
-module(just).
-export([ljust/2, rjust/2, centre/2]).
ljust(String, Width) -> just(String, Width, left).
rjust(String, Width) -> just(String, Width, right).
centre(String, Width) -> just(String, Width, centre).
just(String, Width, Just) ->
if
length(String) > Width -> String;
true -> shift(String, Width - length(String), Just)
end.
shift(String, 0, _) -> String;
shift(String, 1, centre) -> " " ++ String;
shift(String, N, Just) when N > 0 ->
case Just of
left -> shift(" " ++ String, N - 1, Just);
right -> shift(String ++ " ", N - 1, Just);
centre -> shift(" " ++ String ++ " ", N - 2, Just)
end.
==== Wersja 2 (dude) ====
-module(zad3).
-export([ljust/2, rjust/2, centre/2]).
gensp(W) when W == 0 -> "";
gensp(W) -> " " ++ gensp(W-1).
ljust(S, W) when length(S) >= W -> S;
ljust(S, W) -> S ++ gensp(W - length(S)).
rjust(S, W) when length(S) >= W -> S;
rjust(S, W) -> gensp(W - length(S)) ++ S.
centre(S, W) when length(S) >= W -> S;
centre(S, W) -> rjust(ljust(S, length(S) + (W - length(S))/2), W).
===== Zadanie 4. (Ponton) =====
#!/usr/bin/env escript
-import(lists). % tylko do mapa, najwyżywej swojego napisać
main(Args) ->
L = lists:map(fun(X) -> list_to_integer(X) end, Args),
io:format("~w\n", [mergesort(L)]).
mergesort([]) -> [];
mergesort([X]) -> [X];
mergesort(L) when is_list(L) ->
{A, B} = split(L),
merge(mergesort(A), mergesort(B)).
split(L) when is_list(L) -> split(L, [], []).
split([], A, B) -> {A, B};
split([X], A, B) -> {[X|A], B};
split([X,Y|T], A, B) -> split(T, [X|A], [Y|B]).
merge([], X) -> X;
merge(X, []) -> X;
merge([X1|T1], [X2|T2]) ->
if
X1 < X2 -> [X1 | merge(T1, [X2|T2])];
true -> [X2 | merge([X1|T1], T2)]
end.
{{tag>[listy_zadan]}}