Skip to content

Instantly share code, notes, and snippets.

@essen
Created October 14, 2013 03:25
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save essen/6970232 to your computer and use it in GitHub Desktop.
Save essen/6970232 to your computer and use it in GitHub Desktop.
Thinking in Erlang: The Code
-module(my_module).
-export([my_function/1, my_function/2]).
-export([infinite_loop/0, f/1, r/2, sort/1]).
-export([only_primes/1, is_prime/1]).
my_function(A) when is_integer(A) ->
my_function(A, 0);
my_function(A) when is_list(A) ->
my_function(list_to_integer(A), 0).
my_function(A, B) when is_integer(A), is_integer(B) ->
A + B.
infinite_loop() ->
infinite_loop().
f([]) ->
[];
f([H|T]) ->
io:format("head ~p; tail ~p~n", [H, T]),
[H * 2|f(T)].
r(Fun, L) ->
r(Fun, L, []).
r(_Fun, [], Acc) ->
lists:reverse(Acc);
r(Fun, [H|T], Acc) ->
io:format("head ~p; tail ~p; acc ~p~n", [H, T, Acc]),
r(Fun, T, [Fun(H)|Acc]).
sort([]) ->
[];
sort([H|T]) ->
Smaller = [X || X <- T, X =< H],
Bigger = [X || X <- T, X > H],
sort(Smaller) ++ [H|sort(Bigger)].
only_primes(L) ->
only_primes(L, []).
only_primes([], Acc) ->
lists:reverse(Acc);
only_primes([H|T], Acc) ->
case is_prime(H) of
true ->
only_primes(T, [H|Acc]);
false ->
only_primes(T, Acc)
end.
is_prime(N) when N > 1 ->
is_prime(N, 2).
is_prime(N, D) when D > N div 2 ->
true;
is_prime(N, D) ->
case N rem D of
0 ->
false;
_ ->
is_prime(N, D + 1)
end.
-module(mysup).
-export([start/0]).
start() ->
spawn(fun init/0).
init() ->
erlang:process_flag(trap_exit, true),
init_children().
init_children() ->
ChildPid = recv_loop:start_link(),
io:format("~p~n", [ChildPid]),
loop(ChildPid).
loop(ChildPid) ->
receive
{'EXIT', ChildPid, _} ->
init_children();
_ ->
loop(ChildPid)
end.
-module(recv_loop).
-export([start/0, start_link/0, stop/1,
increment/1, get_counter/1]).
start() ->
spawn(fun init/0).
start_link() ->
spawn_link(fun init/0).
stop(Pid) ->
Pid ! stop.
increment(Pid) ->
cast(Pid, increment).
get_counter(Pid) ->
call(Pid, get_counter).
cast(Pid, Msg) ->
Pid ! Msg,
ok.
call(Pid, Msg) ->
MRef = monitor(process, Pid),
Pid ! {Msg, MRef, self()},
receive
{'DOWN', MRef, process, Pid, _} ->
exit(crash);
{MRef, Reply} ->
demonitor(MRef, [flush]),
Reply
after 1000 ->
exit(timeout)
end.
init() ->
loop(0).
loop(Counter) ->
receive
stop ->
ok;
increment ->
loop(Counter + 1);
{get_counter, FromRef, FromPid} ->
FromPid ! {FromRef, Counter},
loop(Counter);
Msg ->
loop(Counter)
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment