isbn.erl: My first Erlang module


Posted

in

,

For a few weeks now I’ve been tinkering with, learning about, and falling in love with Erlang. I’ve been noticing the buzz about Erlang over the past few months, but two things won me over: the Erlang video and how amazingly simple and elegant concurrency and message passing is.

For the past few weeks I’ve been reading the Erlang documentation, Joe Armstrong’s new book, reading the trapexit wiki, and lurking in #erlang on irc.freenode.net. If you’re wading in the erlang waters, I highly suggest just about every link in this wonderful roundup of beginners erlang links.

After a few weeks of reading and tinkering in the shell I decided that it was time to come up with a quick project to hone my Erlang skills. I had tinkered with ISBN validation and conversion while writing a small django application to catalog the books on the bookshelf, so I thought that was a good place to start. The Wikipedia page and my collection of ISBN links provided me with more than enough guidance on validation, check digit generation, and conversion.

I found it very easy to build this module from the ground up: start with ISBN-10 check digit generation, then use that to build an ISBN-10 validator. I did a similar thing with ISBN-13, writing the check digit generator and then the ISBN-13 validator. From there I was able to build on all four public functions to write an ISBN-10 to ISBN-13 converter as well as an ISBN-13 to ISBN-10 converter (when that is a possibility). In the process of this very simple module I ended up learning about and applying accumulators, guards, the use of case, and lots of general Erlang knowledge.

Here’s a peek at how the module works. After downloading it via google code or checking out the latest version via Subversion, the module needs to be compiled. This is easily accomplished from the Erlang shell (once you have Erlang installed of course):

mcroydon$ erl
Erlang (BEAM) emulator version 5.5.4 [source] [async-threads:0] [kernel-poll:false]

Eshell V5.5.4  (abort with ^G)
1> c('isbn.erl').
{ok,isbn}

After that we can use any of the exported functions:

2> isbn:validate_13([9,7,8,1,9,3,4,3,5,6,0,0,5]).
true

Let’s trace the execution of a simple function, check_digit_10/1. The function expects a list of 9 numbers (the first 9 numbers of an ISBN-10) and returns the check digit as either an integer or the character 'X'. The first thing that the function does is check to see if we’ve actually passed it a 9-item list:

check_digit_10(Isbn) when length(Isbn) /= 9 ->
    throw(wrongLength);

This is accomplished with a simple guard (when length(Isbn) /- 9). If that guard isn’t triggered we move on to the next function:

check_digit_10(Isbn) -> 
    check_digit_10(Isbn, 0).

This forwards our list of 9 numbers on to check_digit_10/2 (a function with the same name that takes two arguments. We’ll see in a minute that the 0 I’m passing in will be used as an accumulator. The next function does most of the heavy lifting for us:

check_digit_10([H|T], Total) ->
    check_digit_10(T, Total + (H * (length(T) + 2)));

This function takes the list, splits it in to the first item (H) and the rest of the list (T). We add to the total as specified in ISBN-10 and then call check_digit_10/2 again with the rest of the list. This tail-recursive approach seems odd at first if you’re coming from most any object oriented language, but Erlang’s function nature, strong list handling, and tail-recursive ways feel natural very quickly. After we’ve recursed through the entire list, it’s time to return the check digit (or 11 minus the total modulus 11). There’s a special case if we get a result of 10 to use the character ‘X’ instead:

check_digit_10([], Total) when 11 - (Total rem 11) =:= 10 ->
    'X';

Finally we return the result for the common case given an empty list:

check_digit_10([], Total) ->
    11 - (Total rem 11).

Feel free to browse around the rest of the module and use it if you feel it might be useful to you. I’ve posted the full source to my isbn module at my isbnerl Google Code project, including the module itself and the module’s EDoc documentation. It is released under the new BSD license in hopes that it might be useful to you.

I learned quite a bit creating this simple module, and if you’re learning Erlang I suggest you pick something not too big, not too small, and something that you are interested in to get your feet wet. Now that I have the basics of sequential Erlang programming down, I think the next step is to make the same move from tinkering to doing something useful with concurrent Erlang.

Comments

63 responses to “isbn.erl: My first Erlang module”

  1. Jeremy Avatar

    Great stuff. 🙂

    I was surprised and rather pleased to see my own first dabblings in Erlang on the list of links you linked to.

  2. Mike McNally Avatar
    Mike McNally

    Calling “length()” on each iteration isn’t necessary. You know the length at the start, so you can just pass forward a length with your iteration accumulator.

  3. Mike McNally Avatar
    Mike McNally

    Also, instead of the check digit special case being a separate function body, I’ve grown to prefer using a “case” expression, perhaps like this:

    check_digit_10([], T) ->
    case T rem 11 of
    1 -> ‘X’;
    N -> 11 – N
    end.

    It’s a matter of personal preference of course.

  4. Bill Compton Avatar

    Hi Jim. Photos i received. Thanks

  5. vmqoegiacy Avatar

    Hello! Good Site! Thanks you! qzmgyvrrvz

  6. htcfxrcygz Avatar
    htcfxrcygz

    The Government’s examinations watchdog used the hotels to host meetings in the course of a recent review it was carrying out into the secondary school curriculum. advertisement The full extent of the spending only emerged after a whistleblower within the organisation raised concerns. Matthew Elliott, the chief executive of the Taxpayers’ Alliance, said: “The QCA’s focus should be on improving the qualifications and exams for children in this country, not living the high life at taxpayers’ expense. “If their offices are not large enough for a conference and they need outside accommodation, they should pick cheaper locations rather than frittering away other people’s hard earned cash. “The QCA should show a bit more humility and respect for…http://brendsite.com/

  7. sirf iii gps receiver…

    haha gotta love it……

  8. freedom keychain gps…

    Garmin is one of the most trusted names in the gps industry, and owning a Garmin gps unit is a great step in the right direction with some of the best navigation technology around….

  9. bitiemiapaymn Avatar

    Very nice!!

  10. Катастрофа Avatar

    Автор +1 интересные мысли

  11. Евстафий Avatar

    Ура!, вебмастер голимо опубликовал.

  12. unittrucks Avatar

    Камрад шарит в теме

  13. myVideo Avatar

    На каком-то сайте я уже читал схожую тематику, но все равно спасибо

  14. Иришка Avatar

    Ура!, хозяин сайта четко отжег!

  15. AxiomeAbemymn Avatar

    Ничего себе, автор необычно накреативил.

  16. Alline Hartson Avatar

    titanic account you pick up

  17. Cleopatra Sanchirico Avatar

    Through what medium do top hands run across budget items?

  18. inflatable Rafts Avatar

    Raining like a cow peeing on a flat rock.

  19. Masako Smithson Avatar

    Me and my friend were arguing about an issue similar to this! Now I know that I was right. lol! Thanks for the information you post. To children sleep problems that are a part of their childhood even have a chance at becoming chonic.

  20. weight loss pill reviews Avatar

    Thank you for making the sincere try to give an explanation for this. I think very robust approximately it and wish to be told more. If it’s OK, as you attain extra in depth knowledge, might you thoughts adding extra posts very similar to this one with more information? It could be extraordinarily useful and useful for me and my colleagues.

  21. Online Coupons Avatar

    I believe that is an interesting point, it made me suppose a bit. Thanks for sparking my pondering cap. From time to time I am getting so much in a rut that I just feel like a record.

  22. San antonio bounce house Avatar

    I love the valuable knowledge you offer in your articles. I can bookmark your blog and have my kids test up right here generally. I’m relatively sure they are going to be informed a variety of new stuff right here than anybody else!

  23. NYC Bankruptcy Lawyers Avatar

    I’m speechless. It is a excellent weblog and really enticing too. Nice paintings! That’s now not actually a lot coming from an amateur publisher like me, however it’s all I may say after diving into your posts. Great grammar and vocabulary. No longer like other blogs. You actually understand what you?re talking about too. Such a lot that you made me need to explore more. Your blog has change into a stepping stone for me, my friend.

  24. internet marketing services Avatar

    Glad I detected this on google .

  25. problem water Avatar

    Unusual this submit is totaly unrelated to what I used to be looking google for, however it was indexed on the first page. I suppose your doing one thing right if Google likes you sufficient to place you on the first web page of a non similar search.

  26. cheap propecia Avatar

    I am sorry, that I interrupt you, I too would like to express the opinion.

  27. tax attorney Avatar

    found your site on del.icio.us today and really liked it.. i bookmarked it and will be back to check it out some more later

  28. New York City Bankruptcy Attorneys Avatar

    Good day, I just hopped over in your web site via StumbleUpon. No longer one thing I would normally read, but I preferred your emotions none the less. Thank you for making one thing worth reading.

  29. dead space 2 cheats Avatar

    I’ve been reading your entries right through my morning break, and I must admit the whole article has been very enlightening and really well written. I thought I’d permit you to understand that for some explanation why this weblog does not view well in Internet Explorer 8. I wish Microsoft may prevent changing their software. I’ve a question for you. Could you thoughts exchanging blog roll links? That may be really neat!

  30. lanyards Avatar

    Abnormal this post is totaly unrelated to what I used to be searching google for, but it surely was once listed at the first page. I guess your doing something proper if Google likes you adequate to position you on the first web page of a non similar search.

  31. cao gold Avatar

    Thanks for making the trustworthy effort to talk about this. I believe very strong about it and want to learn more. If it’s OK, as you acquire extra intensive knowledge, would you thoughts adding extra articles similar to this one with additional information? It would be extraordinarily helpful and helpful for me and my friends.

  32. tutoring jobs sydney Avatar

    Thanks for the helpful information! I would not have gotten this myself!

  33. drink Avatar

    The Coming of Age of Garden R‚sum‚ Elisabeth Blair MacDougall was brilliantly a noted a scarcely garden historian.

  34. baseball trading pins Avatar

    I am speechless. It is a superb blog and really enticing too. Nice work! That’s not truly much coming from an novice publisher like me, however it’s all I may just say after diving into your posts. Nice grammar and vocabulary. Not like different blogs. You actually know what you?re speaking approximately too. So much that you just made me want to explore more. Your weblog has become a stepping stone for me, my friend.

  35. tutoring jobs Avatar

    For whatever reason my browser doesn?t display this page properly? Anyway, it had been a very fascinating post, continue the great work as well as I will be back for more

  36. dog tags customized Avatar

    Thank you for making the honest effort to speak about this. I believe very sturdy about it and wish to read more. If it’s OK, as you acquire more intensive wisdom, could you thoughts adding more articles very similar to this one with additional info? It might be extraordinarily useful and useful for me and my friends.

  37. blog home Avatar

    Hello.This article was extremely interesting, especially since I was looking for thoughts on this topic last Friday.

  38. baseball trading pins Avatar

    I’ve been reading your entries all through my morning break, and I must admit the entire article has been very enlightening and really well written. I believed I might will let you realize that for some reason why this weblog does not view neatly in Internet Explorer 8. I wish Microsoft might forestall converting their software. I’ve a query for you. Would you thoughts replacing weblog roll hyperlinks? That will be truly neat!

  39. wholesale ralph lauren Avatar

    Peculiar this post is totaly unrelated to what I used to be searching google for, but it surely used to be listed on the first page. I guess your doing something proper if Google likes you enough to put you on the first page of a non comparable search.

  40. Moving Company NYC Avatar

    City move can be and should be an easy process. With Manhattan Movers NYC it start with call to our office! No hidden costs, no surprices! Call us. We serve Manhattan, Brooklyn, Queens – all NYC. Manhattan Movers NYC, 553 Broome St, New York, NY 10013, (212)300-6628

  41. football Avatar

    I like watching football on bbc football chanel. How about you people?

  42. elation lights Avatar

    Good issues?I would note that as any individual who in point of fact doesn’t write on blogs so much (in truth, this may be my first publish), I don’t think the term ‘lurker’ could be very becoming to a non-posting reader. It’s not your fault the least bit , however perhaps the blogosphere may get a hold of a better, non-creepy title for the ninety% of us that revel in studying the content material .

  43. diamond earrings Avatar

    After reading your post I am sure that i might possibly recognize via school, probably did happen to visit Tx Technical? If you ever did make sure you send myself a message so we can easily get up to date it has been quite a long time! Look forward to conversing with you and wish most is well with you.

  44. Abrareadjoure Avatar

    почерпнул много нового

  45. vigrx pills Avatar

    I’m speechless. It is a superb weblog and very enticing too. Nice work! That’s no longer in point of fact a lot coming from an novice publisher like me, however it’s all I may just say after diving into your posts. Nice grammar and vocabulary. Now not like other blogs. You in point of fact know what you?re speaking approximately too. So much that you made me wish to discover more. Your weblog has turn into a stepping stone for me, my friend.

  46. Susan Avatar

    I found your blog and decided to have a very quick study, I don’t always do this, but this blog is wonderful. Wonderful to see a site that isn’t full of spam, and understandable. Anyway, great write up.

  47. lanyards Avatar

    I admire the precious knowledge you be offering on your articles. I will bookmark your blog and have my youngsters take a look at up here generally. I’m fairly positive they will be told a variety of new stuff here than any one else!

  48. my blog Avatar

    Ordinary this post is totaly unrelated to what I used to be looking out google for, but it surely used to be indexed on the first page. I assume your doing something right if Google likes you adequate to position you on the first page of a non related search.