Steve Yegge wrote about the expressiveness of Ruby as compared to Java. He used this simple problem as an example:
How about if we write a program that will print out all the words in the dictionary starting with the letter ‘Q’ (case-insensitive), grouped by increasing length, and sorted alphabetically within each group.
The Ruby version was about 12 lines of code and Java version about 43. Of course, the point of the exercise wasn’t simply the difference in LOCs, but in the overall simplicity of dealing with collections of data. Still, I wanted to see how Tcl would deal with the same problem. Here’s the simplest version I could come up with:
set f [open /usr/share/dict/words r]
set words [read -nonewline $f]
close $f
set qwords [lsearch -all -inline [split $words \n] {[Qq]*}]
proc compare_length {a b} {
if { [string length $a] <= [string length $b] } {
return -1
} else {
return 1
}
}
set sorted_qwords [lsort -command compare_length [lsort $qwords]]
set max -1 foreach qword $sorted_qwords {
if { [string length $qword] > $max } {
set max [string length $qword]
puts "Words of length $max:"
}
puts " $qword"
}
About 19 lines and pretty simple to write and read. Can this be improved?
Comments from old site
Meditations on programming languages
I like Paul Graham's essays on this subject.
Have you seen this http://paulgraham.com/fix.html or this http://paulgraham.com/icad.html?
Prem Thomas 2006-10-03 14:13:23Tcl functional programming (And the example in Perl)
I don't do as much tcl programming as I used to, but I do do a lot of Perl and some Ruby.
One thing I have really picked up from the Perl community is a love of using functional programming when it makes sense (which is quite a bit). If you want to get into functional programming in tcl there are quite a few good resources on the tcl.tk wiki, but there's also a fantastic functional tcl package in openacs that every openacs programmer should make themselves familiar with:
[ACS Tcl 5.2.0 : ad-functional-procs.tcl - full lambda functions (with no memory leaks, although a bit of memory usage)
Now, onto the fun part! I thought I'd take on the Q word example in Perl. Here's a reasonable way to do it in Perl:
And here's the pathological way :)
Mark Aufflick 2006-11-26 21:49:24More stuff to learn
Thanks Prem for the amusing comments about languages. I still have the "Revenge of the Nerds" on my to-read list.
Mark, that is one scary looking snippet of Perl. :) Thanks for the links to the functional programming procs in OpenACS. I had never seen those. Do you know of any code that uses them?
I've been meaning to learn some more about functional programming, but the going has been difficult. It's definitely a different mindset.
Vinod Kurup 2006-12-14 16:34:02