Finally managed to finish chapter 2
Hereās my solution, which is essentially the same as yours
-module(afile_client).
-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, FileName, FileContent) ->
Server ! {self(), {put_file, FileName, FileContent}},
receive
{Server, Content} ->
Content
end.
-module(afile_server).
-export([start/1, loop/1]).
start(Dir) -> spawn(afile_server, loop, [Dir]).
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, FileName, FileContent}} ->
Client ! {self(), file:write_file(FileName, FileContent)}
end,
loop(Dir).
1> c(afile_client).
{ok,afile_client}
2> c(afile_server).
{ok,afile_server}
3> FileServer = afile_server:start(".").
<0.104.0>
4> afile_client:get_file(FileServer, "afile_server.erl").
{ok,<<"-module(afile_server).\n-export([start/1, loop/1]).\n\nstart(Dir) -> spawn(afile_server, loop, [Dir]).\n\nloop(Di"...>>}
5> afile_client:put_file(FileServer, "new_file.erl", "Some content").
ok
6> afile_client:get_file(FileServer, "new_file.erl").
{ok,<<"Some content">>}
Thoughts so far
Iām loving this book!
I especially like how Joe is expressing whatās what in Erlang in no uncertain terms and I like his analogies. The way he talks about Modules in Erlang being like classes in OOP (and that processes are like objects) and that processes are lightweight virtual machines - I donāt think Iāve heard anyone else say that before.
Like @DevotionGeo I am also growing to like some of Erlangās syntax, for instance I think atoms ( module/function names) being lowercase makes sense in a functional language because you use them a lot as you are forever calling some module:function()
. I can also see why the .
might have been used because it would be handy if youāre sending a lot of commands via a terminal, you could almost ātalkā to it by means of sending the commands as a series of sentences in a paragraph. However I am still unconvinced about it when writing everyday code in files.
I also like how he talks about there being a beautiful symmetry between the client and server - itās just small things like this that help you see the thought behind things and it goes some way to shape the way you feel about things yourself too.
Canāt wait to read more! I bet you are flying ahead @Rainer!!