Erlang Programmingのchapter3のexciseを途中まで

日のErlang Lite #2の予習なんだけど,もう眠くなったのであきらめる!!
なので中途半端に途中までw.

Ex.3-1
%% ex1.erl
-module(ex1).
-compile(export_all).


sum(1) ->
    1;
sum(N) ->
    N + sum(N-1).


sum(N, M) ->
    if N == M ->
	    N;
       N < M ->
	    M + sum(N, M-1)
    end.
Ex.3-2
%% ex2.erl
-module(ex2).
-compile(export_all).


create(0) ->
    [];
create(N) ->
    create(N-1) ++ [N].


reverse_create(0) ->
    [];
reverse_create(N) ->
    [N|create(N-1)].
Ex.3-3
%% ex3.erl
-module(ex3).
-compile(export_all).


printnum(0) -> ok;
printnum(N) ->
    io:format("Number:~p~n",[N]),
    printnum(N-1).


printevennum(0) -> ok;
printevennum(N) when N rem 2 == 0 ->
    io:format("Number:~p~n",[N]),
    printevennum(N-1);
printevennum(N) -> printevennum(N-1).
Ex.3-4
%% db.erl
-module(db).
-compile(export_all).


new() ->
    [].


%% reserved function
destroy(Db) ->
    ok.


write(Key, Element, Db) ->
    [{Key,Element}|Db].


delete(Key, Db) ->
    case Db of
	[] ->
	    [];
	[H|T] ->
	    case H of
		{Key, Element} ->
		    delete(Key,T);
		_ ->
		    [H|delete(Key,T)]
	    end
    end.


read(Key, Db) ->
    case Db of
	[] ->
	    {error, instance};
	[H|T] ->
	    case H of
		{Key, Element} ->
		    {ok, Element};
		_ ->
		    read(Key,T)
	    end
    end.


match(Element, Db) ->
    case Db of
	[] ->
	    [];
	[H|T] ->
	    case H of
		{Key, Element} ->
		    [Key|match(Element,T)];
		_ ->
		    match(Element,T)
	    end
    end.
Ex.3-5
%% ex5.erl
-module(ex5).
-compile(export_all).


filter(List, Target) ->
    case List of
	[] ->
	    [];
	[Target|_T] ->
	    [Target];
	[H|T] ->
	    [H|filter(T,Target)]
    end.


reverse(List) ->
    case List of
	[] ->
	    [];
	[H|T] ->
	    reverse(T) ++ [H]
    end.


concatenate(Lists) ->
    case Lists of
	[] ->
	    [];
	[H|T] ->
	    H ++ concatenate(T)
    end.


flatten(List) ->
    case List of
	[] ->
	    [];
	[H|T] when is_list(H) ->
	    concatenate([flatten(H)|[flatten(T)]]);
	[H|T] ->
	    [H|flatten(T)]
    end.
Ex.3-6 (quick sort)
%% ex6.erl
-module(ex6).
-compile(export_all).


%% WikipediaのErlangのページのコードが参考になる
quicksort([]) -> [];
quicksort(List) ->
    case List of
	[Pivot|Rest] ->
	    quicksort([ X || X <- Rest, X < Pivot]) ++ [Pivot] ++ quicksort([ Z || Z <- Rest, Z >= Pivot])
    end.
Ex.3-6 (merge sort)は前のエントリー参照

Erlangでmerge sortを作ってみる練習