I am learning Erlang and I am trying to create a very sample blog program. However my mind currently is trapped in the OO world (var p = new Post(); p.Title = ""; p.Save();). I would like to understand some basic thinkings in Erlang. Instead of creating Post object what I should do in terms of data structure (p.Title, p.DateCreated, p.Body)? Should I be using tuple? I would like to understand the recommended way in doing such things (in both Erlang specific and or Functional Programming specific). Or is what I am doing fundamentally wrong in either Erlang or FP?
Requirement (in OO terms, not sure how to explain in FP terms yet ^_^):
Thanks.
Updated: I am not looking for specific way of doing OOP in Erlang unless it's the recommended way. I am looking for standard/recommended way of doing what's described in the question, however I am not trying to replicate OOP in Erlang.
Erlang is an Object Oriented language. This statement has more power if you look at OOP the way Alan Kay described it:
OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things.
As you must be aware, Erlang promotes a style of programming called Concurrency Oriented Programming, in which you abstract away objects as independent processes that communicate by message passing. Each process has it's local state, they live in their own parallel world. Dynamic polymorphism is achieved by the fact that, you can define a class of processes that can respond to a common set of messages. As Erlang 'objects' live in their own tiny process, it becomes a natural medium for modelling the real-world. You can make use of your OOP skills better in Erlang than in any other language.
Can't give a full description about OOP in Erlang in such a small space. I suggest that you read the book Programming Erlang: Software for a Concurrent World.
Also see these links:
I would use records:
-record(post, {title, date_created, body, comments = []}).
-record(comment, {created_by, date_created, content}).
Then if you want to use mnesia as database:
Post = #post{title = "", body = "", date_created = erlang:universaltime()},
mnesia:transaction(fun() -> mnesia:write(Post) end).
To add a comment:
Comment = #comment{created_by = "", content = "", date_created = erlang:universaltime()},
mnesia:transaction(fun() ->
[Post] = mnesia:read(post, Title),
PostWithNewComment = Post#post{comments = [Comment | Post#post.comments]},
mnesia:write(PostWithNewComment)
end).
I haven't tested the code, but this is what I would do. Also I assumed that each title is unique.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With