Start programming erlang.

This commit is contained in:
Kyle Isom 2019-04-21 19:25:01 -07:00
parent bb0620f3aa
commit ba841f127c
7 changed files with 97 additions and 0 deletions

1
.gitignore vendored
View File

@ -4,6 +4,7 @@
*.o
*.pdf
.d
*.beam
# ignore build systems
.ninja_deps

25
pe/afile_client.erl Normal file
View File

@ -0,0 +1,25 @@
-module(afile_client).
-compile([debug_info]).
-export([ls/1, get_file/2, put_file/3]).
ls(Server) ->
Server ! {self(), list_dir},
receive
{Server, FileList} ->
FileList
end.
get_file(Server, File) ->
Server ! {self(), {get_file, File}},
receive
{Server, Content} ->
Content
end.
put_file(Server, File, Contents) ->
Server ! {self(), {put_file, File, Contents}},
receive
{Server, Result} ->
Result
end.

37
pe/afile_server.erl Normal file
View File

@ -0,0 +1,37 @@
-module(afile_server).
-compile([debug_info]).
-export([start/1, loop/1]).
start(Dir) ->
spawn(afile_server, loop, [Dir]).
%% Three significant points to observer about this code:
%%
%% + Who to reply to: all the received messages contain
%% the variable Client - the PID of the sender.
%% + Use of self(): the PID of the server.
%% + Pattern matching to select the message.
loop(Dir) ->
receive
{Client, list_dir} ->
Client ! {self(), file:list_dir(Dir)};
{Client, {get_file, File}} ->
Full = filename:join(Dir, File),
Client ! {self(), file:read_file(Full)};
{Client, {put_file, File, Contents}} ->
Full = filename:join(Dir, File),
Client ! {self(), file:write_file(Full, Contents)},
{Client, ping} ->
Client ! {self(), pong};
{Client, _} ->
Client ! {self(), unrecognised_message};
{_} ->
io:format("unhandled message")
end,
loop(Dir).
%% Notes:
%% + function names are always lowercased
%% + universal receiver: receive X -> X end.
%% + erlang: use processes to structure the solutions to our problems.
%% + *ATOMS*ARE*LOWER*CASED*

11
pe/geometry.erl Normal file
View File

@ -0,0 +1,11 @@
-module(geometry).
-export([area/1]).
area({rectangle, Width, Height}) ->
Width * Height;
area({circle, Radius}) ->
3.14159 * Radius * Radius;
area({square, Side}) ->
Side * Side.

14
pe/heads.erl Normal file
View File

@ -0,0 +1,14 @@
-module(heads).
-export([len/1]).
alen([], Count) ->
Count;
alen([_|T], Count) ->
alen(T, Count+1).
len([_|T]) ->
alen(T, 1);
len([]) ->
0.

5
pe/hello.erl Normal file
View File

@ -0,0 +1,5 @@
-module(hello).
-export([start/0]).
start() ->
io:format("Goodbye, joe.~n").

4
pe/shop.erl Normal file
View File

@ -0,0 +1,4 @@
-module(shop).
-export([cost/1]).