Busy making things: github, links, photos, @mc.

isbn.erl: My first Erlang module

Posted: May 3rd, 2007 | Author: | Filed under: Open Source, Projects | 63 Comments »

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.


63 Comments on “isbn.erl: My first Erlang module”

  1. 1 Jeremy said at 11:08 am on May 4th, 2007:

    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. 2 Mike McNally said at 11:18 am on May 4th, 2007:

    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. 3 Mike McNally said at 11:25 am on May 4th, 2007:

    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. 4 Bill Compton said at 2:27 pm on June 4th, 2007:

    Hi Jim. Photos i received. Thanks

  5. 5 vmqoegiacy said at 11:32 pm on July 31st, 2007:

    Hello! Good Site! Thanks you! qzmgyvrrvz

  6. 6 htcfxrcygz said at 10:01 pm on November 25th, 2007:

    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. 7 sirf iii gps receiver said at 1:26 pm on February 12th, 2008:

    sirf iii gps receiver…

    haha gotta love it……

  8. 8 freedom keychain gps said at 4:46 pm on February 15th, 2008:

    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. 9 bitiemiapaymn said at 11:43 am on August 3rd, 2008:

    Very nice!!

  10. 10 Катастрофа said at 8:19 pm on April 13th, 2010:

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

  11. 11 Евстафий said at 6:28 pm on April 28th, 2010:

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

  12. 12 unittrucks said at 2:08 pm on May 17th, 2010:

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

  13. 13 myVideo said at 5:49 am on September 21st, 2010:

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

  14. 14 Иришка said at 9:35 am on September 23rd, 2010:

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

  15. 15 AxiomeAbemymn said at 6:58 pm on September 25th, 2010:

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

  16. 16 Alline Hartson said at 2:04 pm on November 8th, 2010:

    titanic account you pick up

  17. 17 Cleopatra Sanchirico said at 12:06 am on November 13th, 2010:

    Through what medium do top hands run across budget items?

  18. 18 inflatable Rafts said at 11:09 pm on November 25th, 2010:

    Raining like a cow peeing on a flat rock.

  19. 19 baby child health said at 7:57 pm on December 19th, 2010:

    very good \o/

  20. 20 Masako Smithson said at 8:17 pm on January 5th, 2011:

    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.

  21. 21 weight loss pill reviews said at 11:37 pm on January 19th, 2011:

    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.

  22. 22 Online Coupons said at 11:20 am on January 21st, 2011:

    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.

  23. 23 San antonio bounce house said at 1:00 pm on January 21st, 2011:

    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!

  24. 24 NYC Bankruptcy Lawyers said at 12:09 pm on January 22nd, 2011:

    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.

  25. 25 internet marketing services said at 10:36 pm on January 23rd, 2011:

    Glad I detected this on google .

  26. 26 problem water said at 11:25 pm on January 23rd, 2011:

    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.

  27. 27 cheap propecia said at 2:45 am on January 24th, 2011:

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

  28. 28 tax attorney said at 8:25 am on January 24th, 2011:

    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

  29. 29 New York City Bankruptcy Attorneys said at 11:32 am on January 24th, 2011:

    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.

  30. 30 dead space 2 cheats said at 2:01 am on January 25th, 2011:

    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!

  31. 31 lanyards said at 5:50 am on January 25th, 2011:

    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.

  32. 32 cao gold said at 9:30 am on January 25th, 2011:

    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.

  33. 33 tutoring jobs sydney said at 4:54 am on January 26th, 2011:

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

  34. 34 drink said at 6:44 pm on January 26th, 2011:

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

  35. 35 baseball trading pins said at 1:14 am on January 27th, 2011:

    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.

  36. 36 tutoring jobs said at 9:01 am on January 27th, 2011:

    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

  37. 37 dog tags customized said at 2:05 am on January 28th, 2011:

    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.

  38. 38 wXGApuoP said at 9:31 am on February 1st, 2011:

    fLPLaC

  39. 39 blog home said at 2:48 pm on February 1st, 2011:

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

  40. 40 baseball trading pins said at 12:04 am on February 2nd, 2011:

    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!

  41. 41 wholesale ralph lauren said at 2:27 am on February 2nd, 2011:

    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.

  42. 42 Moving Company NYC said at 12:51 pm on February 2nd, 2011:

    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

  43. 43 football said at 9:05 am on February 3rd, 2011:

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

  44. 44 elation lights said at 11:25 pm on February 4th, 2011:

    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 .

  45. 45 diamond earrings said at 9:58 pm on February 5th, 2011:

    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.

  46. 46 Abrareadjoure said at 11:08 pm on February 5th, 2011:

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

  47. 47 vigrx pills said at 2:19 am on February 6th, 2011:

    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.

  48. 48 Susan said at 1:30 pm on February 7th, 2011:

    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.

  49. 49 lanyards said at 10:34 pm on February 7th, 2011:

    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!

  50. 50 my blog said at 10:55 am on February 8th, 2011:

    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.

  51. 51 Lady Gaga said at 5:10 pm on February 8th, 2011:

    I tried to get the feed for the RSS for this webpage & for some odd reason it isn’t displaying in Google Chrome. Does anyone have any ideas???

  52. 52 Beyonce said at 5:31 pm on February 8th, 2011:

    I am a tremendous fan of your weblog! Appear at my site, You’ll be able to check your web page right here!

  53. 53 Justin Bieber said at 5:33 pm on February 8th, 2011:

    I used to be pretty delighted to find out this internet sites on bing.I wished to say a great number of due to you with regard to this outstanding piece!! I surely liked every last small little bit of it and I’ve you bookmarked to have a glimpse at new things you submit.

  54. 54 Pioneer vsx-1020-k review said at 8:52 am on February 9th, 2011:

    Unusual this submit is totaly unrelated to what I was searching google for, nevertheless it was listed at the first page. I guess your doing something proper if Google likes you sufficient to put you at the first page of a non comparable search.

  55. 55 PPI Information said at 9:30 pm on February 10th, 2011:

    this is nice information need to know more

  56. 56 Lady Gaga said at 1:30 am on February 11th, 2011:

    Considerably, the page is actually the sweetest on this noteworthy topic. I harmonise with your conclusions and will thirstily appear forward to your approaching updates. Just saying thanks won’t just be sufficient, for the amazing clarity inside your writing. I will immediately grab your rss feed to remain informed of any updates.!

  57. 57 Lady Gaga said at 2:24 am on February 11th, 2011:

    I realistically like your web log material the way you place up the things…I’ve peruse the matter with wonderful interest.

  58. 58 jammers for sale said at 11:43 am on February 11th, 2011:

    I image this may well be various upon the written content? even so I still consider that it may be suitable for just about any type of topic subject material, because it might incessantly be pleasurable to resolve a heat and delightful face or maybe listen a voice while preliminary landing.

  59. 59 zero friction marketing said at 7:31 pm on February 11th, 2011:

    You completed certain good points there. I did a search on the theme and found nearly all people will consent with your blog.

  60. 60 tory-burch-new-arrival said at 10:39 pm on February 14th, 2011:

    discount tory burch shoes…

    Tory Burch Handbags is a trendy yet durable.Tory Burch is an American fashion designer who got her start on the upper-east side of Manhattan. Tory Burch Designer Handbags are a great collection of high quality fun handbags available in a wide variety o…

  61. 61 tory-burch-reva-flats said at 10:43 pm on February 14th, 2011:

    cheap tory burch shoes …

    As the summer goes, winter comes.You should have some shoes in store. Based on this point, the cheap tory burch shoes Shoes is developing faster and faster. More and more people do online shopping.With so many shoes in it, now I advise you getting a …

  62. 62 web hosting in delhi said at 3:11 am on February 18th, 2011:

    Thanks for making the sincere attempt to talk about this. I think very strong about it and wish to read more. If it’s OK, as you acquire extra intensive wisdom, would you thoughts including extra articles very similar to this one with more information? It might be extraordinarily useful and useful for me and my friends.

  63. 63 CrosbyCasandra said at 8:48 am on February 18th, 2011:

    I took my first personal loans when I was 25 and that aided my relatives a lot. Nevertheless, I need the consolidation loans also.