Monday, October 8, 2007

Reading SICP 1.1.6

This time around, I’ve decided to toss the translations for Ruby, Factor, and Erlang into the same post instead of trying to juggle multiple posts and point them all at one another. So, without further ado …



Section 1.1.6



Let’s take a look at section 1.1.6, the goal of this section is to look at conditional expressions through implementing an absolute value procedure. the book iterates through a couple of versions, trimming away fat. In each of my examples below, I’ve only shown the final product.



In Ruby, the code should look something like this:



def abs(num)
if num < 0
num = -num
end
return num
end


In Factor it looks like this:



: abs ( n -- n ) dup 0 < [ -1 * ] [ ] if ;


And in Erlang it looks like this (I’ve left out the administrative bits from the top of the file):



abs(A) ->
case ( A < 0) of
true -> -1 * A;
false -> A
end.


Exercise 1.3



Esercise 1.3 asks the reader to write a procedure that takes three numbers and returns the sum of the squares of the largest two of them. In each case below, I rely on the previously defined square and sum-of-squares (sum_of_squares) procedures.



Ruby was pretty easy:



def sum_squares_of_larger(a, b, c)
sorted_nums = [a, b, c].sort.reverse
sum_of_squares(sorted_nums[0], sorted_nums[1])
end


Factor took me a while to figure out (mostly in trying to figure out how to build the array):



: top-two ( x,y,z -- x,y ) 3array natural-sort reverse first2 ;
: sum-squares-of-larger ( x,y,z -- x ) top-two sum-of-squares ;


I’m least sure of my Erlang code. I couldn’t find a good function for sorting the array, so I borrowed the qsort function from Programming Erlang. In any case, here’s my cut at it:



qsort([]) ->
[];
qsort([Pivot|T]) ->
qsort([X || X <- T, X < Pivot])
++ [Pivot] ++
qsort([X || X <- T, X >= Pivot]).

last_two([H|T]) ->
T.

sum_of_squares_of_list(L) ->
lists:sum([square(A) || A <- L]).

sum_squares_of_larger(A, B, C) ->
sum_of_squares_of_list(last_two(qsort([A,B,C]))).


What I learned



The biggest thing I’ve taken away from this exercise so far is that I really need a good Factor book that covers both the language and the vocabulary. Along similar lines, Programming Erlang is a good book, but it could have spent some more time on basic programming (especially covering the provided functions in something other than an appendix).



Factor has been the language that’s been hardest to wrap my mind around so far. At the same time, it’s the one that I’ve enjoyed the most—I also think the word definitions have a sort of terse beauty. I think Ruby is probably the one that most programmers could just pick up and maintain though.



Next up, Section 1.1.7 “Square Roots By Newton’s Method”.

Thursday, October 4, 2007

Reading SICP in Erlang: Section 1.1.4

Ok, here’s my erlang take on Section 1.1.4 of SICP, or you can go look at my Ruby or Factor versions.




Unlike Scheme, Ruby, or Factor, I’ve got to put the code for the square and sum_of_squares functions1 into a separate file. I’m not going to explain the mechanics of the file, but we can take a look at the functions themselves.




sicp.erl
-module(sicp).
-export([square/1]).
-export([sum_of_squares/2]).
square(A) -> A * A.
sum_of_squares(A, B) -> sicp:square(A) + sicp:square(B).


square has an arity of 1 (it takes a single argument), and returns the value of that argument times itself. Because mulitplication only works with numeric types, it will work for integers and floats, but will fail for non-numeric arguments.




To execute these functions we need to compile the code (see line 1 below). Then we just call the function (with its module namespace) and give it an appropriate argument.





1> c(sicp).
{ok,sicp}
2> sicp:square(5).
25
3> sicp:sum_of_squares(3,4).
25


And that’s about all there is to it. Pretty simple stuff. Next up will be section 1.1.6 exercise 1.3.




1 In SICP they’re called procedures; in Ruby, methods; and in Factor, words. I just need to try to keep them all straight.

Wednesday, September 26, 2007

Reading SICP in Erlang and Ruby



I’ve had a long standing goal to read SICP, but it keeps conflicting with other goals, like mastering Ruby or learning Erlang (to name a couple of geeky ones). Recently I learned of a project to ‘translate’ SICP into Erlang (and other languages).




“Great! I can use this to help with both learning Erlang and reading SICP”, I thought and went to take a look at it. It turns out they also have a Ruby translation underway, so I went to look at that first. It turns out that the first couple of examples make me think that they either don’t understand Ruby or don’t understand SICP.




Page 5 of SICP shows that you can start up a LISP or scheme interpreter and type in an expression and it will return that expression, like this:


> 486
486
>

The site recommends the following Ruby puts 486, which is not quite right:

irb(main):001:0> puts 486
486
=> nil
irb(main):002:0>

You see, this prints 486, but returns nil. A much better answer looks a lot more like scheme:

irb(main):002:0> 486
=> 486
irb(main):003:0>



With a problem like this early on, I’m not sure that I trust the Erlang or other translations. I do like the idea though, so I should probably stick with my idea of combining the goals, and just post my own translations into Erlang and Ruby (and let everyone else find my mistakes).

Wednesday, September 19, 2007

Long Time No Write

It’s been a while since I’ve written anything here, and (sadly) a long time since I’ve taken any time to focus on Erlang. I’d like to rectify both of these deficencies, so here’s a first stab.




First off, I’d like to drum up another Provo Erlounge for October 9th at 7PM (MST). We can meet at the Open Source Technology Center again (we’re supposed to have wireless access at that point). There are a couple of routes we can go, either hitting the Concurrent Programming and Distributed Programming chapters from Programming Erlang: Software for a Concurrent World or walking through some ‘real world’ Erlang code. Anyone have a request/suggestion for us?




Secondly (and more generally), I’ve recently been talking with a publisher about their entry into the Functional Programming world. They’re very interested in doing this, and seem to have a good plan. They haven’t settled on which language(s) they want to cover yet, but Erlang is on their list. They would like feedback on which languages, potential topics, and potential authors would be of interest. If you’d like to leave a comment here, I’d be happy to pass the information along. If you’re worried about other publishers mining the information (but, hey, that would just mean more potential books on Erlang and FP wouldn’t it?), feel free to email me directly.




And now, it’s off to spend a little time with Erlang.

Monday, June 11, 2007

May Contest Winners



After going through the contest entrants for May, we’ve come to a decision.
Joe, Dave, and I couldn’t decide between an entry on socket programming (which appears to be broken now) and one on ErlUnit.




The writers of these posts should drop me a line to get set up for their free copies of Programming Erlang: Software for a Concurrent World.




If you’re interested in a copy, never fear. The Erlang Blogging contest is still running. Go ahead and write a blog post about Erlang, and add a link to it in the comments below. If you’re post is selected as our June Winner, you’ll win a copy of Joe’s book as soon as it’s in print. Great topics to write about include tools for Erlang programming, tutorials about Erlang modules or software, and tutorials about Erlang itself.




Thanks for the support in May, and good luck to everyone who enters in June.

Thursday, May 17, 2007

Pragmatic Haskell

Wow! Pragmatic Haskell seems like it might be on the way too. I’d love to work with Haskel and Erlang side by side to get a better feel for Functional Programming, and a book by the Prags is probably the only way I’ll get into Haskell—the other books/tutorials I’ve seen just don’t work for the way my brain is wired (I’m guessing that I won’t need a cheat sheet to figure out how to write/read the code in this book).




Now, we just need to watch for an official announcement. I’m hoping it will be a beta book also.

Wednesday, May 9, 2007

Successful Provo erlounge

Well, we got our Utah Valley Erlang group started with a bang—11 enthusiasts showed up (I hesitate to say hackers because most of us are newbies). We had a quick review of Erlang’s history and problem domain, and took a look at some code (the webput.erl example). A couple of folks also got Erlang installed on their laptops.




It wasn’t a bad start, but we’re not nearly done. We’ll be meeting from 7-9PM on the second Tuesday of every month going forward. The Open Source Technology Center has been kind enough to offer us meeting space—they even provided Pizza and soda this time around. For our June meeting, we’re each going to try our hand at writing some Erlang (something that will be run cooperatively over our laptops), then we’ll do a ‘show and tell’/code review. If I can just think of something interesting, but not too hard, it should be a lot of fun.




If you’re interested in joining us please do, we’d love the company. We plan on coordinating our meetings on the erlang-questions list unless we get to big/noisy/rowdy for it.

Tuesday, May 1, 2007

May Blogging Contest

Updated! See below for a clarification.



Programming Erlang:  Software for a concurrent World Programming Erlang: Software for a Concurrent World seems to be bringing a lot of attention to Erlang right now. In hopes of helping some of us newbies stick, I’ve worked out a deal with Dave Thomas, the Pragmatic Programmers are sponsoring a blogging contest over the next three months (May, June, and July). I can almost hear you asking yourselves, “What’s a blogging contest and what does this have to do with me?” Well here’s the deal:




I’d like to invite you to write a tutorial or explanatory post that supports or supplements ‘Programming Erlang’. At the end of each month, I’ll collect the entries and working with another judge (the prags and I are still working out who) will determine the winning entry. The author of the winning entry will receive a copy of Programming Erlang.




For the rest of May, ending at midnight on the 31st (MDT), I’ll be collecting entries in the comments section of this post. In June and July, I’ll put up new blog posts to collect links. I’m looking forward to reading a lot of great blog posts, good luck everyone!



Update:



You should be able to write any introductory to intermediate tutorial about erlang or tools around erlang for your entry. If you want to take a look at the Table of Contents for the book, you could always look here



Alternatively, you could buy the beta (pdf only) and look forward to getting a hard copy once you've written your prize winning entry.

Wednesday, April 25, 2007

Erlang Nights in Utah

Well, it looks like I’m not the only Ruby hacker in Utah that’s looking at Erlang. In the UtahValley.rb’s April meeting, we decided to set up an informal study group to work through Programming Erlang—several of us already have the beta book.




I don’t know if we’ll start on the first or the fifteenth of May, but I do know it will be fun. I’ll plan on posting about them here.

Wednesday, April 18, 2007

Getting to know erlang-mode

The very first errata listed for the beta Programming Erlang: Software for a Concurrent World is that Joe should include a chapter on erlang programming tools, and it specifically mentions erlang-mode for emacs. Being an emacs user, this piqued my interest and I went off in search of it. Here's a quick run-down of what I found.



Installing and Running erlang-mode



erlang-mode is part of the OTP erlang distribution, although it's kind of hidden. Since I compiled and installed my distribution in the /usr tree, All my examples will point there. Even though the needed elisp files are installed and easy to get runing, you'll need to download and install the erlang man pages. I put them in /usr/lib/erlang on my system.



Once the code and documentation is installed, you can set it up by adding the following elisp code to your .emacs file:


;; setup erlang mode
;; add the location of the elisp files to the load-path
(setq load-path (cons "/usr/lib/erlang/lib/tools-2.5.3/emacs"
load-path))
;; set the location of the man page hierarchy
(setq erlang-root-dir "/usr/lib/erlang")
;; add the home of the erlang binaries to the exec-path
(setq exec-path (cons "/usr/lib/bin" exec-path))
;; load and eval the erlang-start package to set up
;; everything else
(require 'erlang-start)

(Feel free to strip out the comments, They aren't in my .emacs file either.)



First Impressions



The first thing that I found to like about erlang-mode was the ability to run an erlang shell inside emacs. Since I like to play in a REPL while I program, having a shell running inside my editor is great. While I normally have my emacs running much larger than this, I wanted to show a full-sized screenshot so you could read the text. Working this way just rocks!



Picture of an emacs session with the erl shell and syntax highlighting



The screenshot above also shows off erlang-mode's syntax highlighting. There are four levels of syntax highlighting ranging from off to 'Christmas Tree Mode' (which is the highlighting level I run in).



Another thing that leaped out at me, was the auto-formatter/indenter that's built into erlang-mode. It was a little bit strange to be typing along and hit an arrow (->) only to have emacs automagically move to the next line and indent for me. I got used to it in a couple of minutes, and realized that I could get to like it — if I felt like it was using good style, it doesn't match up against the example in Programming Erlang: Software for a Concurrent World. Anyone want to weigh in on how good or bad it looks?


qsort([]) ->
[];
qsort([Pivot|T]) ->
qsort([X || X <- T,
X < Pivot])
++ [Pivot] ++
qsort([X || X <- T,
X >= Pivot]).

(By the way, it also automatically creates an indented, new line in a lot of cases. I'm not quite sure what all of them are yet.)



Since I'm on the topic of code formatting, I thought I'd toss out several small but interesting functions.



  • erlang-align-arrows (C-c C-a): I think that well used whitespace can make reading a program easier, and aligning similar parts of a program is one example. Running erlang-align-arrows against this region:

    for(Max, Max, F) -> [F(Max)];
    for(I, Max, F) -> [F(I)| for(I+1, Max, F)].

    sum([H|T]) -> H + sum(T);
    sum([]) -> 0.

    map(_, []) -> [];
    map(F, [H|T])-> [F(H) | map(F, T)].

    will reformat it to look like this:

    for(Max, Max, F) -> [F(Max)];
    for(I, Max, F) -> [F(I)| for(I+1, Max, F)].

    sum([H|T]) -> H + sum(T);
    sum([]) -> 0.

    map(_, []) -> [];
    map(F, [H|T]) -> [F(H) | map(F, T)].


  • erlang-generate-new-clause (C-c C-j): This command (and the next one) will likely save some typing. It generates a new clause in the curent function, immediately below the current clause, and puts the point at the argument list inside the parens. For example, running erlang-generate-new-clause with the point on the rectangle clause of the following function:

    area({rectangle, Width, Ht}) -> Width * Ht;
    area({circle, R}) -> 3.14159 * R * R;
    area({square,X}) -> geometry:area({rectangle, X, X}).

    will create:

    area({rectangle, Width, Ht}) -> Width * Ht;
    area() ->
    area({circle, R}) -> 3.14159 * R * R;
    area({square,X}) -> geometry:area({rectangle, X, X}).

    One small gotcha is that there's no closing punctuation for the generated clause, so you'll need to type your own semicolon or period.


  • erlang-clone-arguments (C-c C-y): This command will insert the arguments from the previous clause at the current point. If you run it immediately after the erlang-generate-new-clause command above, you'll the new clause will be changed to read:

    area({rectangle, Width, Ht}) ->

    which would be easy to edit to create a triangle clause.



One set of commands I didn't play with were the compilation commands. Once I get to that section of Programming Erlang: Software for a Concurrent World, I'm sure I'll dig back in — I'll plan on writing another post about erlang-mode then.



I hope this was useful. I think I'll be spending a fair amount of time in erlang-mode, so I plan on getting comfortable here. Happy hacking!

Tuesday, April 17, 2007

Why

Ok, so I've settled on Erlang as the functional language I'm going to study this year. I'm not really going to jump in until May, but I'll play in the wading pool until then.



I'll be using Programming Erlang: Software for a Concurrent World as my study guide, along with any good looking blogs/websites I track down while I'm working on it. I've already seen Dave Thomas' two posts on Erlang (A First Erlang Program and Adding Concurrency to Our Erlang Program) and Yariv Sadan's blog looks good too. If I'm missing some good blogs/resources, please, let me know.



I'll track my progress here. Don't expect any whiz-bang results right away, but hopefully it will be both interesting and useful (at least to other Erlang newbies out there).

Erlang and Haskell Books: First Impressions

I recently picked up a beta copy of Programming Erlang: Software for a Concurrent World to go along with my (paper) copy of Programming in Haskell. I figured if I had both books, I could make quick runs through them as I try to decide between Haskell and Erlang as the FP language I'm going to focus on this summer. What follows isn't really a review of either book, just a few first impressions.





Programming Erlang: Software for a Concurrent World looks like to be a very accessible book, that also goes into enough depth to be worthwhile. The version I got yesterday had 279 pages in the PDF, but an update was released today and my new copy hasn't found it's way here yet. I like what I've read of Joe Armstrong's writing and examples, and have caught on quickly to the initial concepts.





Programming in Haskell surprised me by being really small, only 171 pages (including the index). It on the scale of 'The C Programming Language', and so far it reminds me a lot of that book. I have to admit though, that I've always been put off by the seeming need of Haskell writers to use 'special Haskell characters' in their text, Programming Haskell even includes a table of 15 such symbols and how to represent them in ASCII. Bleargh!



So far, I'm leaning towards Erlang (mostly because of concurrency), but I'm not going to make up my mind for a while yet — too many other deadlines I need to deal with right now. As I get closer to the summer, I'll let you know which way I decide to go. (I'll also get real reviews of the two books up fairly soon.)