Slashdot Mirror


Purely Functional Data Structures

andrew cooke writes "A while ago I read the comments following a Slashdot book review. Someone had posted a request for books that covered a wider range of languages than Java, C, Python, etc. Well, I thought, why not review Okasaki's Purely Functional Data Structures? It's a classic from the underworld of functional programming - recognised as the standard reference, yet clear enough to work as an introduction to the subject for anyone with a basic functional programming background. Of course, some readers won't know what functional programming is, or what is special about pure data structures. So I hope that this review can also serve as something of an introduction to the languages that I (a software engineer paid to work with Java, C, Python, etc) choose to use in my spare time, just for the joy of coding." Read on for the rest; even if you're not planning to give up C or Perl, there are links here worth exploring. Purely Functional Data Structures author Chris Okasaki pages 220 publisher Cambridge University Press rating 8/10 reviewer Andrew Cooke ISBN 0521663504 summary Functional programming for grown-ups.

In Okasaki's introduction he says that the "[...] benefits of functional languages are well known, but still the vast majority of programs are written in imperative languages such as C. This apparent contradiction is easily explained by the fact that functional languages have historically been slower than their more traditional cousins, but this gap is narrowing."

Indeed, OCaml has a reputation for being "as fast as C," yet it contains automatic memory management and supports object-oriented, as well as functional, programming. It's also probably the most widely used functional language outside academia (except perhaps Lisp/Scheme).

I mention OCaml not just because it's fast, free and popular, but because Okasaki uses a related language - ML - in his book. The ML family of languages are the standard strict, functional languages (Standard ML of New Jersey is perhaps the reference implementation but see also standardml.org). Okasaki also includes an appendix with examples in Haskell, which is the standard lazy functional language.

The difference between lazy and strict languages is the order in which code is evaluated. Most languages are strict. Unlike most languages, Haskell only evaluates something when it is absolutely necessary. Each parameter to a function, for example, is passed as a "thunk" of code, not a value. If the value is not required inside the function, the parameter is left unused; if it is required (say as part of a result that needs to be displayed) then the thunk is evaluated. This evaluation may trigger a whole slew of evaluations of functions that "should" have been called earlier (from a Java programmer's point of view).

Laziness is both good and bad. The bad side is obvious: the order in which code is executed my be very different from the order in which the program was written and some serious book-keeping is necessary in the compiler to juggle the thunks of code and their final values. The reordering of code could cause mayhem for IO operations, for example (in practice, of course, Haskell includes a solution to this problem).

The good side is that laziness can help make programs more efficient and, while the definition of ML doesn't include laziness, individual ML implementations -- including OCaml and SML/NJ -- include it as an extra.

Much of Purely Functional Data Structures (the second of three parts) focuses on how to use laziness to make data structures efficient. Lazy evaluation allows book-keeping actions to be postponed, for example, so that the cost of maintaining the data structure in an efficient form can be averaged across several read/write operations (improving worst case limits - avoiding a very slow response if the data happen to be in a "bad" order).

An understanding of how the efficiency of algorithms is rated (the big-O notation) is one piece of knowledge that this book does assume, along with a basic grasp of what Stacks, Queues, Trees, etc, are.

This lazy boost in efficiency is needed because, even though functional languages may be getting faster, it's not always possible for them to implement the efficient algorithms used in imperative (non-functional) programming.

But I'm getting ahead of myself, because I haven't described what a functional language is, or why it is useful. These are the topics of the first part of the book, which explains how functional languages, which make it impossible to change variable values by direct assignment, support persistent data structures. This section is fairly brief, and while it's a good refresher course for someone who's not had to worry about such things since studying at university, it's not sufficient as an initial introduction to functional programming in general.

There's a good explanation of functional programming in the Wikipedia, but, in all honesty, I don't see how anyone can really "get it" without writing functional code (just as I, at least, couldn't understand how OOP worked until I wrote code that used objects).

So forgive me for not telling you why functional programming is good (This paper is one famous attempt), but perhaps a better question to focus on is "Why should you spend the time to investigate this?" The best answer I can give is that it leads to a whole new way of thinking about programming. Describing functional programming as "excluding assignment to variables" doesn't do justice to the consequences of such a profound change (one I found almost unimaginable - how can you program without loop counters, for example?).

There's a practical side to all this too - learning new ways of thinking about programs makes you a better programmer. This ties in closely with the final part of Okasaki's book, which explores a few fairly esoteric approaches to data structures. Who would have thought that you can design data structures that parallel the way in which you represent numbers? Some of this is pretty heavy going - I can't say I understood it all, but I'm taking this book with me on holiday (it's slim - just over 200 pages) and I'll be bending my brain around some of the points in the last few chapters as I lie in the sun (here in the southern hemisphere it's late summer).

So just who would benefit from this book? It seems to me that it's most valuable as a second book on functional programming. There are a bunch of texts (and online guides) that can get you started in functional programming. This one goes further. It shows how to exploit the features of functional languages to solve real problems in applied computing. Admittedly, they are problems that have already been solved in imperative languages, but you might find that you, too, come to enjoy those famous benefits of functional languages. The algorithms in this book let you enjoy those benefits without paying the price of inefficiency.

Andrew Cooke last reviewed for Slashdot The Aardvark is Ready for War . You can purchase Purely Functional Data Structures from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

86 of 427 comments (clear)

  1. Purely *Functional* Data Structures by Orne · · Score: 4, Funny

    As opposed to what, Data Structures that don't work? Yeah, we need more books on those...

    1. Re:Purely *Functional* Data Structures by MooseByte · · Score: 5, Funny

      "As opposed to what, Data Structures that don't work? Yeah, we need more books on those..."

      Fear not, MFC is extensively documented.

      (Complains I, recently bit by yet another lame long-acknowledged-yet-unfixed bug in M$'s class libraries.)

    2. Re:Purely *Functional* Data Structures by Michael+Iatrou · · Score: 2, Funny

      Have you tried Microsoft Press?

    3. Re:Purely *Functional* Data Structures by I_Love_Pocky! · · Score: 5, Insightful
      I never got a Comp-Sci degree myself

      Then how the heck do you know what the teachers are teaching? Maybe you have only talked to the morons who go through comp-sci thinking it is a programming degree. I know that there was a large percentage of people I went through school with who chose to ignore things like functional programming simply because they had the mind set that they were there to get a software development job after school. It was taught, but it mostly fell on deaf ears. If it wasn't c++/MFC they thought they wouldn't need it (and hence spent no time trying to learn it). They were the same crop of students who thought it was stupid that they had to take differential equations and physics, because they would never use that in "the field." They just wasted their education.

      I personally thought it was really interesting, and as such I am now a graduate student. I love comp-sci for what it actually is, which is not programming.

      Why am I replying to a troll??? Oh well, I feel better now.
    4. Re:Purely *Functional* Data Structures by Anonymous Coward · · Score: 2, Informative
      As opposed to what

      Just to make sure everyone knows, it's as opposed to imperative data structures. "Imperative" refers to code that works through updating variables. OO languages such as Java and C++, and languages like C and Pascal are imperative. "Functional languages" do not support updatable variables.

    5. Re:Purely *Functional* Data Structures by AKAImBatman · · Score: 4, Interesting

      You think I don't know comp-sci? Oh dear, we seem to have a pickle here. I must have chosen the wrong profession, because I could have sworn I was leading teams of developers, doing my part to change the fact of Java gaming, helping design better database drivers, competing in competitions to pack the most into 4K, building better tools, and generally spending my time trying to knock some sense into these idiots who didn't pay attention when they were getting their degrees.

      I didn't get a degree, but I did take the hard way of learning comp-sci. I spent years of my time studying the various texts and papers that students *should* be studying. Some people complain that, "well you can't be a *true* comp-sci professional because you didn't pay for this piece of paper." I just shake my head at their insecurity and offer to help them solve whatever their current problem is.

      There are my credentials. Take them or leave them. My only recommendation is that you don't underestimate what I can do, or what I have done.

    6. Re:Purely *Functional* Data Structures by pclminion · · Score: 3, Insightful
      "you don't know anything about calculating algorithms to execute at O(n), O(log n), O(1), etc."

      Knowing what the term means, and knowing how to actually prove that an algorithm is O(x), are two different things. Can you prove that general sorting cannot be less than O(n log n)? This is fundamental. If you can't do it, you do not know computer science. (Flip side of coin: if you can, then you are at least heading the right direction).

      "game programming is not real comp-sci!" (tell that to my collision algorithms or research into better timing methods)

      A hobbyist tinkering in the garage does not a scientist make. Put out a publication comparing your methods with other known methods. Give theoretical upper and lower bounds on run time, memory usage, jitter, etc. Criticize yourself and explain the defects in your methods. Submit it to peer scrutiny. That's science.

    7. Re:Purely *Functional* Data Structures by AKAImBatman · · Score: 4, Interesting

      Can you prove that general sorting cannot be less than O(n log n)? This is fundamental. If you can't do it, you do not know computer science

      Yes, I can. And that's my point. I learned how when I was given my first book on data structures. It was a little weird at first, but if you're going to do things right, you have to know the math behind them. In fact, modern computers long ago made me give up the desktop calculator. Trying to develop for the processing power of today requires numbers far beyond what my old desktop calculators could do. It's too bad, because it was so convenient to not have to switch windows. And yes, I'm too cheap to get a decent scientific calculator. :-)

      Put out a publication comparing your methods with other known methods.

      You mean like this one? Looking back at it, I should have taken the time to clean up the english. I was so excited about my algo, that I just pushed it out. :-)

      Keep an eye on Java Developers Journal for an article on logging. They wouldn't let me publish a pure research paper, but I was able to squeeze in a dissertation on using ThreadLocals for multiplexing a stream.

      Does anyone know any *good* comp-sci journals? Dr. Dobbs looks promising, but I had already promised an article to JDJ.

    8. Re:Purely *Functional* Data Structures by aafiske · · Score: 2, Funny

      Actually I'd prefer a book on Purely Fictional Data Structures. You know, like Hobbit Hair Queues and Keebler Elf B-Trees.

      Sorry, I'll stop now.

    9. Re:Purely *Functional* Data Structures by sketerpot · · Score: 2, Interesting
      I think it may be possible to get pretty far on borrowed intuition. For example, I'm learning some computer science on my own. The other day I wrote my second symbolic differentiation program, and it was pretty elegant---mainly because I remembered the organizational plan from a textbook.

      Still, I wouldn't bet on it. It could be that you can only go so far with borrowed aesthetics. But it may be farther than I would think.

  2. Over where I work by Anonymous Coward · · Score: 5, Funny

    Management prefers dysfunctional programming.

  3. I don't even see the code.. by laurent420 · · Score: 5, Funny

    blonde... brunette..

  4. Nice Review! by jaaron · · Score: 5, Informative

    Nice to see some actual content on Slashdot!

    By the way, this reminds me of the recent article on Domain Specific Languages over on Martin Foweler's website. Another aspect of programming worth investigating.

    --
    Who said Freedom was Fair?
    1. Re:Nice Review! by YoJ · · Score: 4, Informative
      This is one of my favorite books, and is largely responsible for me switching from math to CS. I had done C and Java programming before, but I always considered programming (and computer science) a messy but fun engineering activity akin to woodworking. When I read this book, I got a glimpse of the "true meaning" of programming.

      I would recommend this book to programmers that have a couple years experience with imperative or OO languages, who have also taken an introductory course in algorithms. A motivated reader does not need experience with ML, but having taken some sort of "Programming Languages" class that spends a day or two on ML is very helpful. I found it the most rewarding to learn ML and start programming in ML while reading this book, then attempting to implement the data structures in the book myself to use in small projects.

      If you don't know any functional languages and don't want to learn them, this book will not be helpful and you probably won't get enough motivation from the book itself to understand what it's talking about. If you don't really know functional languages but are willing to give them a try, this book is ideal. If you already know one or more functional languages well, you should try to read Okasaki's papers on functional data structures before getting the book. Of course you might want the book too.

    2. Re:Nice Review! by jdavidb · · Score: 2, Insightful

      I don't see how it's "flamebait" or "troll." Apparently functional programmers can't see past "defense of the functional paradigm of programming."

      Don't you understand? I want to be one of you; I want to be a functional programmer. I want to know what this book is about and if it can help me get into functional programming. I already know there's something special and wonderful to be gained from the functional paradigm. I don't need an introduction to functional programming or a defense of its merits. What I need is a description of what's in this book. (My thanks to the user who posted the book's table of contents. That was far better than the review.)

      I guess some folks are so busy dividing up the world into "friends" and "enemies" that they can't figure out how to just provide information. Obviously, since I didn't rave about how great the review was, I must be an enemy of functional programming and deserve to be modded down.

      How can this review be so great when the reviewer didn't even talk about the book? I'd probably willingly agree the book was great if I could know what was in it, but this review told me next to nothing. The people who've said the review is great are really commenting on the quality of the book, not the review; almost all of them say they've already got it.

    3. Re:Nice Review! by sfogarty · · Score: 2

      I'm inclined to agree... but hopefully I can help. This book is my bible, given as my primary interest is functional algorithms. The topics covered are, as you might expect, data structure based, and focused on 'concepts' rather than 'reference'. He doesn't give complete implementaitons of a lot of the structures, leaving it more as an excercise (there is no deletion in the red-black trees), and there is a lot of analysis. The first bit discusses basic imperitive data structures, and how to code them functionally, making it not too hard to start with if you're not familiar with the topic... not to say that you shouldn't already know functional programming and data structure design. The two 'big' (read new) things in the book are layaway ammortization, which can be used persistantly, and a discussion of math-inspired structures deriving from binomial heaps. If you want more information on it, feel free to email me.

  5. O'Camel by Robert+Webb · · Score: 4, Interesting

    Is 'OCaml' pronounced 'Oh-Camel', 'Ach-amel'...? Akin to the 'Line-Ux' versus 'Lin-Ux' confusion.

    --
    I recommend Thin Client's and Fat Fiber!
    1. Re:O'Camel by Anonymous Coward · · Score: 3, Informative

      You read it like OKamell with a french accent (its developers are french).

    2. Re:O'Camel by sjlumme · · Score: 2, Interesting
      It's pronounced "oh camel", i.e. *not* as a fictitious Irish surname but as an analogue to ACaml, BCaml, CCaml...

      The big difference between OCaml and Lisp/Scheme is that even though both are *strongly* typed, that is, you can never, say, reference memory address pi becaus a float is simply not a pointer, they work it in different ways. Lisp/Scheme is dynamically typed, like Python, and stores the types with the values, which are checked at runtime. OCaml is statically typed, which means it does not need to store types in tags, but analyzes your program at compile time to ensure "type safety".

      On the one hand, this gives a performance win. On the other hand, it makes programming slightly more painful at times. The expression "if x=3 then 5 else 2.0" is not acceptable to the OCaml compiler, because it cannot determine its type; the expression (if (eq? x 3) 5 2.0) is perfectly acceptable to a Scheme compiler. The advantage of this, it is claimed, is that most programs without well-defined types are buggy anyhow, so it helps you write good code.

      Note that the same performance win can be had from not having the language be very precise about types at all, and randomly allowing dereferencing of integers and multiplication of pointers. The archetype for that, of course, is C, which is considered *weakly* typed (a.k.a. "wrongly typed"). This has the disadvantage that programs can behave unpredictably and cause system crashes very easily. If an OCaml or Scheme program ever segfaults, let alone causes a bus error, that's a bug in the compiler. If a C program does that, well you all know what that means...

      Just to confuse you a little more, there's yet another distinction to be made, which is between explicitly and implicitly typed. A language such as C or Java is explicitly typed, meaning that you have to declare variables and functions as being of a certain type, although the explicit types in C are mostly sugar and can always be overridden. Python and Scheme are implicitly typed, that is, you don't mention any types, which is not a big deal, since there really is only one type. All right, backtrack. I just said they had type tags, and now I say there's only one type? The answer to that is one of terminology. From a theoretical perspective, if any slot can contain any value, there's only one type (like Java's Object).

      Now OCaml is statically, strongly *and* implicitly typed. That means that it will check at compile time that there can be no type errors, and you don't even have to mention the types. Say you write a funtion in OCaml like this: let f x = 2 * x . Then it will derive for you that it has type Int -> Int. This is accomplished through a piece of higher math called Hindley-Milner type inferencing.

      If you are interested in this sort of stuff, I strongly recommend Lambda the Ultimate (lambda.weblogs.com), which is always full of programming language reading material, both on a very abstruse theoretical and on a very practical level.

  6. Misread Headline by glarvat · · Score: 2, Funny

    At first I read the headline as "Purely Fictional Data Structures."
    I was really confused for a minute thinking, "What do ficticious data structures have to do with ML or Lisp?"

    1. Re:Misread Headline by yerfatma · · Score: 2, Funny

      They're especially good for handling release dates.

  7. Not a typewriter by JoshuaDFranklin · · Score: 5, Funny
    But I'm getting ahead of myself, because I haven't described what a functional language is, or why it is useful. These are the topics of the first part of the book...

    You know, your computer is not a typewriter, so you really could have rewritten that part of your review...

    1. Re:Not a typewriter by ornil · · Score: 5, Funny

      He did, but because of lazy evaluation it ended up after the second part.

  8. I like any language by donnyspi · · Score: 5, Funny

    that supports GOTOs. Those are the best!

    1. Re:I like any language by Waffle+Iron · · Score: 3, Informative
      that supports GOTOs. Those are the best!

      Well, the functional language Scheme supports "continuations". These are kind of like GOTOs on acid.

  9. Functionals by SparafucileMan · · Score: 3, Interesting
    Functional languages fucking 0wn. They are, generally, easier to write, maintain, read, understand, and debug than the procedural nonsense that has dominated programming (due solely to the historical problems of making computers fast and having nothing to do with best theoretical practices). Now, if someone would just re-start production of LISP machines (updated for modern functional languages), nearly all of us would be better off.

    1. Re:Functionals by ill_mango · · Score: 4, Interesting

      Are you serious?

      I agree that functional programming languages are quite useful, but speaking as a coder who learned functional programming just last year in class, I can say that functional languages are a lot more complicated than procedural languages.

      Sure, once you get good at it you can bang out a functional program easily, and maintenance can be a breeze once you know how to write the code. However, reading and understanding code that ISN'T yours can be damn near impossible sometimes, especially when you're a newbie.

      I'm not discounting the use of functional languages, I'm just saying they are harder to learn than procedural languages.

    2. Re:Functionals by SparafucileMan · · Score: 4, Informative
      Its a different mind-set required to write in a functional language, that's all. Some people find it a steeper learning curve, and some don't. But the effort put into learning the functional language style will be paid back 1,000 fold (at least) for the rest of your life, whereas learning a typical procedural language will only get you 10x return. Plus the pay-back on learning the functional language will apply to _all_ languages you ever learn. This is because all languages and algorithms are defined, on paper, in a functional style anyway (since it uses "math"), and the procedural super-set is just a needless complication from what is 'really happening'.

      But then again, I majored in math, not programming, so maybe I'm biased.

    3. Re:Functionals by e4liberty · · Score: 2, Informative

      Having delivered commercial (yes!) applications on Lisp Machines, I can say with some authority that a G4 Mac with Digitool's Macintosh Common Lisp (MCL) is an excellent, probably superior substitute.

      The folks at Digitool, and Gary's OpenMCL is a nice free alternative if you don't need the GUI.

    4. Re:Functionals by Kupek · · Score: 5, Insightful

      I agree that functional programming languages are quite useful, but speaking as a coder who learned functional programming just last year in class, I can say that functional languages are a lot more complicated than procedural languages.

      I don't know how you can say that the languages are more complicated. Scheme, for example, is the simplest language I know of, in terms of syntax and semantics.

      I think you're confusing this with how difficult it is to think functionaly when you've been raised to think imperatively. Functional programming is a different paradigm than imperative programming, and as such, you have to think differently. If you've been programming imperatively for a while, learning another imperative langauge is often straight forward; you learn the basics of the syntax, what the language provides natively, and how you can construct what it does not provide. You already know how to solve problems with that style of language.

      Learning a functional language, however, is more than just having to learn a different syntax and set of rules (assuming you've been raised imperatively). You have to learn a different way of solving problems. And until you've done that for quite some time (I, for example, have not), I don't think you're qualified to make the judgement calls you did.

    5. Re:Functionals by Arcanix · · Score: 3, Interesting

      Of course they are harder for you to learn. I had the same problem, we were both taught first on an imperative language and so forever more we are stuck on that mindset.

      People I have met who started out on functional and can write a lisp program as quick as I can write C often have serious problems with even the simplest program imperative languages just as I will get stumped by something stupid when trying to use lisp.

      As in natural languages it is normally your first language that you are going to be comfortable with the most although you can obviously learn others. In coding its a bit more complex since you may find that your first language was terrible and pick up another one but people will generally stay in the same paradigm of imperative, functional or OO. It is a challenge to cross over once your mind works in a certain way.

    6. Re:Functionals by hc00jw · · Score: 2
      However, reading and understanding code that ISN'T yours can be damn near impossible sometimes, especially when you're a newbie.

      That's a bit harsh! Isn't this true of all programming languages?

      Think of it this way, because there is much less code to write, and you shave off all the fluff and get to the point, surely that makes the code easier to read, because you're not left scratching your head and asking why certain counters are included, what a variable is set as at any one point in the program (this is due to it's strong typing of course). Sure, there are still certain concepts to understand with functional programs that aids your reading of other peoples code... But then, that's the same with programming in general anyway!

    7. Re:Functionals by Temporal · · Score: 4, Insightful

      If you only just learned it last year in class, no wonder you find it complicated. You probably have much more experience with imperative languages. Indeed, when you think about programming, your thoughts are probably imperative. Just as a native English speaker might think Japanese is complicated (even after "learning it in class last year"), a native imperative programmer will find functional programming difficult at first.

      You know how they say, once you know one programming language, learning another is easy? Yes, once you know C++, picking up Java is a sinch, and you can probably even read someone's Python code without even learning the language first. But, this is because all of these languages are imperative. If someone tells you to write something in LISP, you may be able to figure out the syntax pretty easily, but no doubt you'll find yourself using imperative constructs like "progn". And, when you do that, the language seems very difficult to use indeed, because it was never supposed to be used that way. I made this mistake once myself.

      Anyway, point is, it's not really fair for you to be judging functional languages until you've practiced them as much as the imperative ones. Personally, my imperative experience still dwarfs my functional experience by a factor of thousands... but I've now convinced myself that, for most purposes, functional languages are superior.

    8. Re:Functionals by Anonymous Coward · · Score: 5, Insightful

      but speaking as a coder who learned functional programming just last year in class, I can say that functional languages are a lot more complicated than procedural languages.

      Wouldn't you be a little bit more qualified to comment if you had several years of experience with both functional and imperative languages, first?

    9. Re:Functionals by gangien · · Score: 5, Informative

      I can say that functional languages are a lot more complicated than procedural languages

      What?? More complicated? No no no.. They are certainly not more complicated. For instance the funcitonal languages:

      (display "Hello World") -Scheme

      main =
      do
      putStr "Hello World" - Haskell

      vs

      #include
      main () {
      printf("hello world"); }- C

      #!/usr/bin/perl
      print "hello world"; - perl

      Now those differences are subtle, but A. The functional languages are easier to read(and I think most any none biases person would aggree with me) B. No whacky syntax, hell scheme syntax is only () C. The data types are simple, Pointers? please. Ect ect. The thing that makes functional programming difficult is the lack of an imperative control flow. Which is how people tend to solve problems. For instance if you want to sum up the numbers 1 through 8, in an imperative language it'd be

      tol = 0
      for i = 1 to 8
      tol += i
      end for

      in scheme it'd be
      (define (sum a b)
      (if (equal? a b)
      b
      (+ a (sum (+ 1 a) b)))

      which is confusing. And not obvious. But as for other people's code, that is always the case. Well I've never seen a language that oculd get around that anyhow, the closest I think is java.

    10. Re:Functionals by QuantumFTL · · Score: 2, Interesting

      I agree that functional programming languages are quite useful, but speaking as a coder who learned functional programming just last year in class, I can say that functional languages are a lot more complicated than procedural languages.

      I'm not sure I'd consider most functional languages complicated. Look at the number of types and basic functions in something like SML or OCaml... a few basic types, and a few functions to act on them... There's really not a lot there to learn.

      If anything many functional programs are simpler because they directly map to the mathematics of the algorithm given... especially for recursive algorithms!

      I believe that often times it's more difficult to program in, but that's hard the same as "complicated".

      Sure, once you get good at it you can bang out a functional program easily, and maintenance can be a breeze once you know how to write the code. However, reading and understanding code that ISN'T yours can be damn near impossible sometimes, especially when you're a newbie.

      Actually one of the main problems that is noticed within the functional community is that because there's a lot of recursion and tight coupling between different parts of algorithms, they can be hard to maintain. That's why a lot of people are excited about monads. They allow the use of modularity in a very cool, and appropriately mathematical way! You should check them out of you haven't already, they greatly simplify the task of writing things like interpreters, etc.

      I'm not discounting the use of functional languages, I'm just saying they are harder to learn than procedural languages.

      I'm not really sure that's true. I know people who's first programming language was functional, and they found it equally hard to move to a procedural language - worrying about things like state, ordering, pointers, globals, memory management, bounds checking, interrupts and callbacks and non-persistent data structures, and even manually-implemented laziness.

      Advanced features of any language are difficult to learn, but I'd suggest that anyone who knows a little math can learn to write a small but useful functional program as easy or easier than they could in something like C. Not to mention many algorithms are so naturally recursive, but tail-recursion optimization doesn't seem to work well on many C compilers.

      It's certainly different though!

      Cheers,
      Justin Wick

    11. Re:Functionals by bigbadbob0 · · Score: 2, Informative
      Your scheme sum example runs fine for small summations. But for big numbers you'll blow the stack because you aren't tail recursive... a "better" solution to sum between a and b:

      (define (sum a b)

      (define (sum' mysum iter)
      (if (> iter b) mysum
      (sum' (+ mysum iter) (+ iter 1))
      )
      )
      (sum' 0 a) )
    12. Re:Functionals by Dasein · · Score: 2, Interesting
      Ack! Using examples with side-effects to demonstrate functional programming! Sheesh. Try this on for size (from the About Haskell page):

      Quicksort in Haskell
      qsort [] = []
      qsort (x:xs) = qsort elts_lt_x ++ [x] ++ qsort elts_greq_x
      where
      elts_lt_x = [y | y <- xs, y < x]
      elts_greq_x = [y | y <- xs, y >= x]
      Quicksort in C
      qsort( a, lo, hi ) int a[], hi, lo;
      {
      int h, l, p, t;

      if (lo < hi) {
      l = lo;
      h = hi;
      p = a[hi];

      do {
      while ((l < h) && (a[l] <= p))
      l = l+1;
      while ((h > l) && (a[h] >= p))
      h = h-1;
      if (l < h) {
      t = a[l];
      a[l] = a[h];
      a[h] = t;
      }
      } while (l < h);

      t = a[l];
      a[l] = a[hi];
      a[hi] = t;

      qsort( a, lo, l-1 );
      qsort( a, l+1, hi );
      }
      }
      --
      You are not a beautiful or unique snowflake -- but you could be if you got off your ass.
  10. What is the world coming to? by TwistedSquare · · Score: 3, Funny
    A while ago I read the comments following a Slashdot book review

    Next thing we know, people will start reading the books as well!

  11. This was a great review by jkauzlar · · Score: 5, Interesting
    I've been learning OCaml on my own for the past several weeks and I've been wondering many of the things that this book seems to address, such as how the functional paradigm solves common problems differently than the imperative. I know first-class functions can significantly reduce the amount of code needed in many procedures...

    I guess what I'm saying is that I've used languages like Perl and Python considerably and ignored the functional aspects of the language, probably much to my disadvantage. I think a good study of a purely functional language could really improve my perl, python, or ruby.

    1. Re:This was a great review by SparafucileMan · · Score: 5, Insightful
      Actually perl has an alternate syntax that includes a functional language, and, of course, you can always write a functional language in perl. But most Perl code online (CPAN) isn't written like this, which pretty much defeats the purpose.

      For example, where I work, I have to write in ColdFusion sometimes. ColdFusion has 2 syntaxes: a tag-based one that looks like HTML and is four times redudant and impossible to deal with, but is easier for people, and a second syntax with first-order functions. Writing in the first-order function syntax is easier, more efficient, clearer, and easier to debug in everyway, except all my co-workers write in the tag syntax, which forces me to, as well. It sucks.

      The point is that programs tend to be written to the lower-common-demoninator of the language, which makes the difference between functional, procedural, and oo languages so huge when there is really no difference.

    2. Re:This was a great review by tcopeland · · Score: 4, Interesting
      > I think a good study of a purely functional
      > language could really improve my perl,
      > python, or ruby.

      Right on. Here's a quote from Yukihiro Matsumoto, creator of Ruby:
      Learn more than one programming language, preferably many different styles, like scripting, object-oriented, functional, logic, etc.
      There's an Artima article where he gives some of his reasons for this idea. That whole series of interviews with him is pretty good.
    3. Re:This was a great review by SparafucileMan · · Score: 3, Informative
      I should have included this link:

      Perl Contains the Lambda Calculus.

      Working with the Lambda Calculus on a computer, as a mathematician who is used to only the brain and pen/paper, makes me alternatively want to piss my pants and orgasm everywhere. It's, like, the simplest programming language on the earth!

  12. eek! by happyfrogcow · · Score: 2, Funny

    article... triggering... college... flashbacks.


    ..must.. resist...


    ..cannot.. fight.. functional


    ..language.. tempatation...



    *head explodes*

  13. The memories... by kneecarrot · · Score: 4, Insightful

    I took a course back in university that used Scheme to teach some programming concepts. As with any course, we had to use Scheme to solve some problems on coding assignments. I remember a general rule everyone learned in the class: if your solution to the problem was more than a handful of lines, it was probably wrong. The solutions were very elegant, but very difficult to debug and very difficult to reason about.

    --

    I always save my last mod point to mod up a good troll. You people are too serious.

    1. Re:The memories... by hc00jw · · Score: 3, Interesting
      The solutions were very elegant, but very difficult to debug and very difficult to reason about.

      Just to clear up, this is because of the lazy evaluator. Because code is executed until it needs to be, you never know what's happening when. For example:
      System.out.println("I have reached this point");
      would be meaningless in a functional program, because from where was this code executed? Hence, not only have you got to re-learn how to write your programs, you have to re-learn how to debug them!

      (As a footnote, I'd say the advantages (lazy evaluation, advanced pattern matching functions, less code, recursion, etc.) outweigh the disadvantages (hard to debug) by a mile!)

    2. Re:The memories... by johnnyb · · Score: 2, Interesting

      "The solutions were very elegant, but very difficult to debug and very difficult to reason about."

      If you get the right mindset, recursive solutions as employed in scheme are very easy to reason about and get correct. The reason is that you can use formal proofs to _prove_ the correctness of your code. You can use the mathematic principles of induction to prove that your code is correct, but only in a purely functional atmosphere.

      It takes a little getting used to if you are an imperative programmer, but its worthwhile.

      However, I will say that the indentation practices of most Schemers is dreadful, and is one of the reasons why tab characters should not be directly equivalent with 8 characters. You see, if you make a tab equivalent to "arbitrary indentation of one level", then the user can set their own tab stops, and when a statement gets unwieldly and deep, you can just shorten the indentation to 1 or two spaces. But when you need some whitespace to view the algorithm better, you can expand it to 4
      or 5, or even 8.

    3. Re:The memories... by Jagasian · · Score: 2, Insightful

      That is not true at all. Lazy evaluation is deterministic and sequential.

      With Monadic programming in a purely lazy functional programming language like Haskell, you can place print statements in your code for debugging... though such a practice isn't even considered good in imperative programming, let alone functional programming.

      Also, since languages like Haskell are pure, adding print statements into your code will most likely change the various types of functions. In other words, a function that returns an integer and a function that returns an integer and prints something - both such functions have different types in Haskell.

      It is easy to debug functional programs, if you have a trace debugger, i.e. a debugger that shows the evaluation step by step and lets you skip evaluation of subexpressions.

      Please give me an explicit example as to why lazy programs are difficult to debug.

    4. Re:The memories... by monadicIO · · Score: 2, Insightful

      The solutions were very elegant, but very difficult to debug and very difficult to reason about.

      The difficulty of debugging scheme arises from the fact that it isn't a statically typed language. Errors such as trying to get the cdr of an atom are caught only at runtime (unless you've got some sort of "soft" typing as done in Dr. Scheme environments, for example). As opposed to this, Caml/SML/Haskell are typed languages, and that avoids a major source of errors and debugging. Once you're past the typechecker, the errors are all logical (no programming language can help you there).

      As for difficulty to reason about, well, notwithstanding the claims of FP coders that all FP programs are self-documenting, it can get quite difficult once you have to deal with higher-order functions that have escaping values. Functional programming is often combinator heavy and trying to read someone elses code is not always easy (I don't have an equal amount of experience with
      OO/Procedural/Functional paradigms to give a sensible comparison).

      --

      The law of excluded middle : Either I'm foo or I'm foobar

    5. Re:The memories... by haystor · · Score: 2, Interesting

      Non recursive problems can be handled with functional languages quite well generally.

      After just a few weeks of programming seriously in Lisp, I found it easier to debug than languages I've used for years. The reason for this is that everything is a function. You can unit test practically everything. You can try it out from the interactive loop.

      My typical hard to find bugs at the beginning were typically because I was using the language wrong, not because I was using the syntax incorrectly. A good example of this would be using a counter combined with a while loop instead of recursion or my favorite, the loop facility.

      --
      t
  14. Translation of Okasaki's sources from SML to OCAML by bcolflesh · · Score: 2, Informative
  15. It's all in the constructors by skybrian · · Score: 4, Informative

    Another way to think about functional programming is as constructor-based programming. Problems are solved by constructing lots of temporary objects that are a little closer to the solution, until you're finally in a position to construct the answer.

    You can do this in any language, but to be efficient, you need an good garbage collector and a compiler that can optimize out most of the temporary objects.

  16. Just got this book by QuantumFTL · · Score: 4, Informative

    Nice review!

    I just got this book and it's clear the author has really done his research. His writing style is also very clear, concise and well thought out. Not overly chatty or pandering, yet not dryly accademic either. Precisely the kind of computer book I'd want to write!

    I'm glad the reviewer didn't try to talk a lot about why people should be interested in functional programs, however I must say that the ability to write large complex algorithms in very few lines, and prove mathematically that it works is simply a miracle in some situations. If you need to write a compiler (or do any other set of complex alogirthms on large recursive data structures, especially those that could take advantage of tagged unions, like Abstract Syntax Trees do) you should check out OCaml. And it doesn't hurt that it can figure out the type of all your functions and variables for you :)

    Oh, and if you happen to get this book, and want to play with OCaml, you can get the OCaml translation of the data structures in this book here.

    I dont' know if very many programmers will ever program in a purely functional language, however it seems that languages of the future will have to include things like first class functions and closures, as they are incredibly useful. I know Ruby and Python already support a lot of it.

    Oh and in case anyone's wondering, it *IS* possible to encapsulate things like notion of state, error handling, and I/O in a purely functional language ("side effect free" language) using something called monads. Now there's a fun concept to wrap your brain around!

    Hope some people here are brave enough to dig into a book like this that requires a bit of math, and more than a little faith at some points :)

    Cheers,
    Justin Wick

    1. Re:Just got this book by illustir · · Score: 2, Interesting
      Oh and in case anyone's wondering, it *IS* possible to encapsulate things like notion of state, error handling, and I/O in a purely functional language ("side effect free" language) using something called monads. Now there's a fun concept to wrap your brain around!
      If someone can explain monads to me in an understandable fashion, I'll be eternally grateful.
      I tried to read that part of the tutorial a couple of times but I got my brain fused ever time.
      --
      -- Alper
    2. Re:Just got this book by QuantumFTL · · Score: 3, Interesting

      Wow, that was fast! Are you browsing Slashdot from the bookstore?

      No no no... I just got the book a few days ago and have been reading it. I've forced myself to play around with OCaml and various functional languages for the last month or so to try out the paradigm, and I must say I'm impressed by the compact expressivity, and the safety of these languages.

      I love the idea of writing programs that can't crash (well, they can hang but they can't segfault), and being able to so elegantly describe an algorithm that I might as well just be writing the math.

      I'm also not exactly upset by the type-inference (I never have to specify the type of almost *ANYTHING* despite the fact that there's no implicit casting). Also being able to make functions that are polymorphic in extremely complex ways allows me to keep algorithms much more general. Functors, for those that havne't used them, are simply awesome. Think templates but done right.

      We need more good book reviews like this. Slashdot should hire the guy :)

      Cheers,
      Justin Wick

    3. Re:Just got this book by Jagasian · · Score: 4, Informative

      Monadic programming is a fancy name for a pretty common sense design pattern used by functional programmers far before the theory of Monads was created. Basically you want a function that executes a list of commands, but the problem is that functions can only evaluate to pure values. So what you do is your function evaluates to a value that represents the list of commands you wanted to execute.

      So the design pattern consists of using functions that pass a state value in and out of each function, in addition to possibly other values. The pattern enforces some restrictions, one of which is: each state value can only be used once.

      So executing one command and then another involves each command being defined as a function that takes the world's state and returns the world's state after modification. Sequencing the two commands then consists of composing the functions such that the state is passed from one function to the next.

      There are additional properties required for something to be considered a Monad... and it turns out that this "design pattern" is a mathematical construct known from a branch of mathematics known as Category Theory, and that category theory construct is called a "Monad".

      A side note: category theory is basically the study of mathematical design patterns. Its more than that, but thats a good intuition for computer scientists to take when they study category theory.

    4. Re:Just got this book by QuantumFTL · · Score: 4, Informative

      Monadic programming is a fancy name for a pretty common sense design pattern used by functional programmers far before the theory of Monads was created. Basically you want a function that executes a list of commands, but the problem is that functions can only evaluate to pure values. So what you do is your function evaluates to a value that represents the list of commands you wanted to execute.

      What makes them special is the mathematical rigor that *ensures* the properties you need from the monads, and greatly aids in proving properties of your algorithms. Things like associativty, and the left/right unit properties really help trivialize a lot of programming proofs.

      It's more than just a "fancy name", and I'd say the most exciting thing about it is that it allows the use of composition of monads to compose functionalities described inside them. It makes functional programs much more modular because of this, and allows one to add all kinds of features to something like an interpreter without hardly changing the signatures of any functions! Quite impressive compared to the normal craziness associated with refactoring a functional program.

      It's interesting to see how monads are used in Glassgow's Haskell compiler... much more useful than I ever though "some weird triple thing" from category theory could be.

      A side note: category theory is basically the study of mathematical design patterns. Its more than that, but thats a good intuition for computer scientists to take when they study category theory.

      I always thought Category Theory was best though of by CS students as a replacement for Set Theory that has a function-centric view... a more pure theory of functions (with applications to the lamda calculus no less) that can usefully find common structure in many disparate fields of mathematics, especially discrete math.

      Cheers,
      Justin Wick

  17. I bought this book by johnnyb · · Score: 4, Informative

    I bought this book about 6 months ago. I *love* it. The author did an excellent job showing many interesting algorithms. I did have to read it a few times to make sense of it, as I am not as engaged in the functional programming community as I would like. I still have trouble figuring out how to apply the banker's method and the physicist's method when determining the amortized performance of functional algorithms.

    Anyway, the book was a great read. I was really surprised to learn how efficient some of the functional data structures could be.

    Good discussion as well on the use of suspensions (lazy evaluation for specific blocks of code) in programming.

  18. Online version available by johnnyb · · Score: 5, Informative

    Also, since this was this guy's thesis, it's also available online

    See http://www-2.cs.cmu.edu/~rwh/theses/okasaki.pdf.

    I suggest you get the book, however, as it's a great read.

  19. Another Book ... by Anonymous Coward · · Score: 2, Informative

    "A while ago I read the comments following a Slashdot book review. Someone had posted a request for books that covered a wider range of languages than..."

    Well he why not try "Comparative Programming Languages" it covers most of them.

    Here is an excerpt:

    "This book considers the principal programming language concepts and how they are dealt with in object-oriented languages such as Java and Delphi, in traditional procedural languages such as Pascal, C and Fortran, in hybrid object-oriented or object-based languages such as C++ and Ada 95, in functional languages such as ML and in logic languages like Prolog. "

    There is also a link to it:

    http://www.cs.stir.ac.uk/~rgc/cpl/

    which I post as plain text because I'm lazy right now and also because I hope this prevents compulsive clickers (are there such people?) from going there without getting too much wisdom out of it. There is after all this much feared slashdot effect.

    Have fun

  20. Cool languages, but why... by chamilto0516 · · Score: 2, Interesting
    These agile/functional languages are great. And noteworthy, non-trivial systems have been written in them. The best part is that they can almost all be used inside of other apps as the "scripting" language. In one of our apps, users could use ECMA Script or Python (actually Jython). We eventually dropped Python because no one used it and the the next generation of our tool dropped ECMA Script because it was not considered mainstream (regardless of many lines web developers are writing and browsers executing at this very moment) and we took hits for that. The current generation of that tool uses Java only.

    I enjoy learning new programming languages but because of stuff like this, I wonder why I should. I still will because I have done non-trivial stuff in them very easily but it is a big downer. At least they let authors write neat books for us geeks to take on vacation.

    --
    Magic Eight Ball: Outlook not so good., Hmmm, how about Excel and Word?
  21. Scala by Channing · · Score: 3, Informative

    Have a look at Scala if you are looking for a language that supports both paradigms.

    From their site:

    Scala is a pure object-oriented language in the sense that every value is an object. Types and behavior of objects are described by classes and traits. Class abstractions are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance.

    Scala is also a functional language in the sense that every function is a value. Scala provides a lightweight syntax for defining anonymous functions, it supports higher-order functions, it allows functions to be nested, and supports currying. Scala's case classes and its built-in support for pattern matching model algebraic types used in many functional programming languages.

  22. But what data structures? by QuantumFTL · · Score: 4, Informative
    This review was awesome, but he didn't really mention what data structures are discussed. Here's the list from the TOC for those who care:

    Heaps:
    • Leftist
    • Binomial
    • Splay
    • Pairing
    • Skew Binomial
    • Lazy Pairing

    Trees:
    • Binary Search
    • Red-Black
    • Trie

    Queues:
    • FIFO
    • Banker's
    • Physicist's
    • Double Ended


    There's also a lot of other things, such as some interesting ways of doing numerical representation in functional languages (lazy numbers!) Even talks about trinary/quaternary numbers, as discussed before on slashdot.

    Also if you'd like to see the source code without buying the book (you cheap bastard!) you can find it here.

    But I hope you buy the book :)

    Cheers,
    Justin
    1. Re:But what data structures? by QuantumFTL · · Score: 2, Informative

      IIRC Osaki said there were some data structures he did not know how to implement in a pure functional language, but I don't think he said which. Are there any obvious gaps in the TOC given by the parent?

      Splay Trees weren't mentioned in the TOC but I haven't gotten thruogh the whole book yet...

      He does say that persistent arrays were about impossible to implement functionally except with a horrible access time. Random Access Lists are used instead (forgot to include that in my list).

      Not sure what else is missing... I didn't see skiplists anywhere in there or any other randomized data structures, but that might have been a matter of personal taste on his part. He also didn't talk much about perfectly-balanced search trees (expensive in imperitive langauges, rediculously so in functional languages).

      Good question though!

      Cheers,
      Justin Wick

  23. A coder's hobby by Bohnanza · · Score: 2, Insightful
    I (a software engineer paid to work with Java, C, Python, etc) choose to use in my spare time, just for the joy of coding.

    So this is what computer programmers do in their spare time - program computers! WooHoo!

    --

    -----

    Sorry, I'm only a 1336 h4x0r.

    1. Re:A coder's hobby by RPoet · · Score: 2, Interesting

      Yeah, can you imagine working with something you enjoy that much? It's preposterous.

      --
      "Oppression and harassment is a small price to pay to live in the land of the free." -- Montgomery Burns.
    2. Re:A coder's hobby by jejones · · Score: 2, Insightful

      So this is what computer programmers do in their spare time - program computers! WooHoo!

      You should qualify that; it's what good programmers do in their spare time.

      "Thank ye, Sir! It'll give me time to catch up on my technical journals!" --Lt. Cmdr. Montgomery Scott, "The Trouble with Tribbles," ST:TOS

  24. Functional Programming missed the boat by Ars-Fartsica · · Score: 4, Interesting
    I was weaned in college on Haskell, and I love it still, but the bottom line is that the programming language industry is a fashion industry. Functional languages are lacking a big corporate/open source backer to glamorize and promote their goodness. Java is a perfect example of how you can hawk a programming language to saturation regardless of its relative merits.

    Network effects are what rules the programming tools industry. Network effects are whim to fashion. Fashion is ruled by those with the legitimacy to glamorize.

    1. Re:Functional Programming missed the boat by The+Pim · · Score: 4, Insightful
      If you examine these "fashions", you'll see many examples of Philip Greenspun's adage that "The exciting thing in computer science is always whatever we tried 20 years ago and didn't work". Industry is ever rediscovering and popularizing old ideas from academia. Even Java, while primitive, took some of its main selling points (garbage collection, portable bytecode) from the ivory tower. In Paul Graham's words, "the default language, embodied in a succession of popular languages, has gradually evolved toward Lisp". These are different ways of saying that if the ideas are good (and good ideas abound in the functional programming community), the mainstream will pick them up eventually.

      Also, it's not exactly true that functional programming lacks a big-name sponsor. Haskell research and implementation is largely driven by Microsoft Research. This is not the same as promoting (something like) Haskell to working programmers, but it suggests that Microsoft has its eye on doing so someday.

      --

      The evaluation of an action as 'practical' . . . depends on what it is that one wishes to practice.
    2. Re:Functional Programming missed the boat by Kyouryuu · · Score: 2, Interesting
      I don't think that's necessarily the case. Java and other languages have become popular because it is relatively simple to understand and can do things that are expected of real-world programs, like graphics. How many OpenGL interpretations done entirely in Scheme can you count? What about basic Windows applications?

      Furthermore, I think it's also the result of software firms wanting to segment many areas of a program into smaller compartments. OOP makes this easier by enforce abstract and interface types, such that there is reasonable expectation that if someone codes under a given construct, it will work as needed. Based on UML diagrams, it is also far easier to break part programs using an OOP language and blueprint them. Can you imagine the nightmare of doing a large project like Doom 3 in Scheme, with so many functions defined on-the-fly and passed to and from other functions?

      Scheme and others have their place in the world in teaching newcomers to think recursively. This is a very useful way of thinking in any language. Common problems often have very elegant solutions in Scheme, and diving into the mindset of functional programming is essential for any serious programmer. But I believe the nature of the language holds it back. Granted, once you know what you're doing, it's not so difficult. But it would seem somewhat unintuitive to plan and design large commercial projects around these languages.

  25. Re:I heard this mentioned on some previous article by catamorphism · · Score: 2, Interesting

    See Simon Peyton-Jones et al's paper "Improving the world's most popular functional programming language: user-defined functions in Excel". (It's just a coincidence that he works for Microsoft Research, really!)

  26. Monads are trivial. by Kickasso · · Score: 3, Informative

    Really. Try this one: http://www.nomaware.com/monads/html/index.html

  27. XSLT by Black+Perl · · Score: 2, Funny

    I think a good study of a purely functional language could really improve my perl, python, or ruby.

    A good study of the purely functional language XSL will really improve your appreciation of perl, python, or ruby!

    --
    bp
  28. Now what I'd like to see by OpMindFck · · Score: 2, Funny

    is Purely Fictional Data Structures.
    Just think of the Zen Koan Binary Tree.

    --
    Sipping on Jolt and Dew. Laid back. With my mind of my cubicle and my cubicle on my mind.
  29. Hard to use in the "real world". by Godeke · · Score: 4, Informative

    I love functional programming. If I had my way, my projects would all use functional programming languages. I don't have my way however, and there are two reasons.

    1. Few commercial tools: Functional languages are under represented in the commercial space. With the exception of Franz Lisp and a few other lisp dialects, there is little commercial support. That may not be a killer for everyone, but I would like an environment with a good form designer and a large library to back me up. One I could give to another coder and expect them to be productive with it. Emacs works as an IDE for me, but I can't force that on others...

    2. Fewer programmers: The vast majority of programmers seem unable/unwilling/whatever to grasp the concepts and work with functional code. If you need to build a team of programmers, it is much harder to find those who can do functional programming (and when you do, they rock, but are expensive and in high demand).

    In the end, I use commonly used commercial tools so I can work with other people. Internally I use a lot of non commercial tools (LAMP model) and so I can sometimes indulge in my functional side there, but rarely can I do functional programming for my business clients.

    --
    Sig under construction since 1998.
  30. Took Okasaki's data structures course by philgross · · Score: 5, Interesting
    Here's a reason to get a Computer Science degree at a good school: you can take a course on data structures taught by Chris Okasaki, the book's author. I took Advanced Data Structures from him at Columbia in 1999. Now he's at West Point.


    The course was pretty mind-blowing. He knows his stuff. It was a bit freaky to watch him grading programming assignments by just reading them, not running them, and yet never missing a mistake.


    I would recommend the book not just as an introduction to advanced data structures in functional languages, but as a guide to some of the more interesting data structures of the last fifteen years, regardless of implementation language.


    -- Phil Gross

  31. The tyranny of momentum: why Ocaml is not popular by zeno_lee · · Score: 4, Informative

    Programming in a functional language allows you to be more concise and expressive. Some studies indicate that development time is 4 times shorter, and the resulting code is 4 times smaller and is much easier to read.

    Take a language like Ocaml.

    It is a functional language with imperative features (loops, mutable data structures), modular organization, has object orientation, compiles to portable byte code (like Java and the JVM) as well as compiling to native code that runs as fast as C, has garbage collection, and a good standard library.

    I'm thinking the reason why there are such few people picking up functional programming is the same reason the US still uses the imperial system for measurement.

    While the rest of the world is on the metric system, the U.S. still uses the strange imperial system, that uses things like 12 inches to a foot, 3 feet to a yard, 16 ounces to a pound. That's because the US is entrenched in a mindset and there's no driving reason to change. This is the same reason why people have been stuck on imperative languages. Imperative languages have been the overriding paradigm because in the past, processing time and memory were expensive and imperative languages. This is no longer the case but there is a huge momentum of imperative language that that rolls on like a giant snowball, reinforced by industry and entrenched upon the next generation of computer programmers.

    How did I discover Ocaml?

    I was investigating rapid prototyping languages to add to my toolbelt and ran across Ocaml. I was drawn to it because it has done extremely well in the ICFP contests, especially in the lightning division (24 hour submission).

    Also it ranks impressively in the great language shootout by Doug Bagley, in terms of Lines of Code, Execution Speed, and memory consumption.

    http://www.bagley.org/~doug/shootout/

  32. Letting you in on a little secret by GodSpiral · · Score: 3, Interesting

    OOP SUCKS!

    Encapsulation is a restriction not a benefit.
    Just as non-open source software allows your data to be held hostage by the class producer authors.
    Reusability is poor because while both Accounting and Genealogy software might use a person object neither is interested in holding the other's baggage.
    An object hierarchy becomes a house of cards, built on excruciating desicions of what to include and exclude at each level, and how much baggage to bring along.
    Really the only good that ever came out of OOP was a straightforward way of passing around references to the same data, and easily creating and destroying records from classes.

    <a href="http://www.lua.org/home.html">Lua</a&g t; is probably the best syntactically designed language out there in terms of both expressive power and readability.

    It has an easy to read vb/pascal like syntax without semicolons.
    It has full functional powers
    No silly restrictions such as immutable variables.
    Tables as a replacement to both lists, and classes,
    essentially fully associative keyed lists
    and since any value can be a function a Table can act as a "method" container.
    Powerful extention mechanisms to define class inheritance/relationships within the language itself (rather than the compiler).
    great calling convention with multiple assignment/return values.

    Lua is a great introductory language, in that it is exceptionally readable. While you will immidiately gravitate to using functional paradigms, you're not forced to using them exclusively. It has elegant OOP and imperative paradigms as well.

  33. Re:functional algorithms by Mr+Smidge · · Score: 2, Funny
    I was taught functional programming by a rather camp lecturer, who spoke with a lisp (no pun intended), and I could never keep a straight face whenever he said 'bottom'. Nor when he pronounced 'sqrt' as 'squirt'.

    He once defined a function called 'my', and then proceeded to use the unfortunate expression "squirt my bottom".

    Now, whenever I see Haskell, I see it as being just riddled with sexual innuendo that I can't get out of my head.....

    > minus x = x - 1
    > lubricated x = x == 0
    > harder x y = x * y
    > stop = 1
    > my x = x
    > bottom = my

    > but thrust =
    > let deeper = minus thrust
    > in my bottom (if lubricated thrust then stop else thrust `harder` (but deeper))


    Nah, nothing dodgy about that at all..
  34. Good book? Yes. Useful? Not really. by Junks+Jerzey · · Score: 2, Interesting

    The majority of this book is devoted to esoteric data structures. Sure, it starts with queues and stacks, but most of the book is devoted to exotic forms of trees and tries and heaps and so on. Very interesting stuff. In reality, though, you get by with a small subset of data structures: arrays and lists (both of which can be thought of as stacks or queues), binary trees, and hash tables / dictionaries. Almost always, once you start delving into crazy forms of trees, you can jump straight to a hash table and be done with it. Purely Functional Data structures is very light on information about hashing.

    I'm speaking from experience as both a functional and imperative programmer. While I have enjoyed the book, I didn't find it to be something that I keep returning to over the years.

  35. Prefer databases by Tablizer · · Score: 3, Interesting

    Over the years I have grown more fond of databases over "data structures". I know this will probably start a holy war, but at least let me express my viewpoint.

    Relational tables are more stable as requirements change. Relational tables are mostly designed around the quantity of relationships between things, such as one-to-many, many-to-many, etc. They are NOT dictated by how they are actually used in a given application for the most part. This at first sounds bad, but it is good because normalized tables transcend specific uses, and are thus more flexible and change-friendly. Relational tables are to describe nouns and facts about nouns, not reflect specific tasks or usages. Thus, you don't end up with "pointer messes".

    For example, if you want to represent a graph with dedicated data structures, you might be tempted to make a list of lists, where one list is the ID's (or pointers) to other nodes (links). But if one is later required to put weights on these links, then a list is no longer appropriate, and you have to overhaul your structures and code that references them. However, a (properly normalized) relational database would use a many-to-many table to represent the links. Adding a weight factor is a trivial column addition. Existing code still works without change (as long as it does not reference or need weight info of course).

    However, SQL and tradition has "bulked up" databases beyond what they need to be for many applications. A light-duty "local" relational engine to complement or replace "big-iron" RDBMS would be nice. I used to use "nimble table engines", and they were easy-to-use and relatively quick. SQL is not the ideal relational language, especially for smaller DB engines. I would like to see the industry explore alternative relational languages. Then we could get away from the pressure to use dedicated data structures. I find them archaic, to be frank. Let's move on.

  36. I have implemented some of these in Ocaml by j+h+woodyatt · · Score: 3, Interesting
    If you're interested in Objective Caml, I have implemented some of the data structures mentioned in this book, i.e. just the ones I wanted the most.

    Red-black binary tree

    Skew-binomial heap

    Real-time catenable deque

    They're buried in a library containing a lot of other goodies that I haven't ported to all the platforms where Ocaml runs. The data structure modules are pure Ocaml, though- so, you can just lift them. The library is BSD licensed (two-clause), so take all the liberties you want as long as you give me props in your distribution and you can cope with the fact that you get NO WARRANTY from me. (It would be nice if you told me you were using it too-- that would help motivate me to care about timely release of updates.)

    * The real-time deque is not technically a pure functional data structure since it uses lazy evaluation for handling concatenation, but- to be fair, a lot of the algorithms in Okasaki's book have a similar property. He is, of course, careful to distinguish the difference between pure and non-pure functional data structures.

    --
    jhw
  37. The heap algorithms in Scheme by jasoegaard · · Score: 2, Informative

    Okasaki's book is delightful. Anyone interested
    in data structures owe themselves read his book.

    I became so inspired that I implemented all the heap
    algorithms in Scheme:

    http://www.scheme.dk/heaps-galore/heap.scm

    The code contains implementations of the following heaps:

    - leftist heaps
    - binomial heaps
    - pairing-heaps
    - splay heaps
    - lazy binomial heaps
    - lazy pairing heaps
    - skew binomial heaps

    The documentation is here:

    http://www.scheme.dk/heaps-galore/doc-heap.txt

    --
    -- A Mathematician is a machine for turning coffee into theorems. - Paul Erdös
  38. Mathematica? by gardyloo · · Score: 2, Informative

    I've just started consciously focusing on functional programming techniques in Mathematica . It's almost religiously advanced in most of the Mathematica texts I've read as being easier to read and, ultimately, faster to program than most procedural algorithms one could implement to do the same things. I've definitely adopted it for some operations on lists and things, but I'll have to get more comfortable with it to apply it to everything I do in Mm . As far as I know, the Mathematica Journal even has a column devoted to solving problems with "one-liners", using only functional programming techniques. (Of course, if one is really interested in it, he could go to Journal of Functional Programming and educate us all.) I'm too cheap to find out for sure.

    It seems to me that Mathematica is extremely powerful in this respect: one can choose which paradigm to program in, and successfully mix paradigms, almost to the heart's content, and get useful information out. Of course, the execution speed may not be so hot, but for ease of use, it can't be beaten. What other programs out there allow such mixing?

  39. Let me also try to explain why FP is good by Tom7 · · Score: 3, Informative

    Regarding write-once variables: the reviewer makes it sounds as though this is some terrible burden or restriction that functional programmers must deal with. I offer the contrary point: immutable structures are an *invariant* that make programming much, much easier. Have you ever been in a situation where some other part of the code has an alias to something you're working with, and is modifying it when you don't want it to? Functional programming totally avoids that by having a language-enforced invariant of immutability.

    That (along with all of the other features that functional languages typically have that languages like Java and C don't, like higher order nested lexically-scoped functions, polymorphism, algebraic data types and pattern matching, parameterized modules, tuple and sum types, etc.) is the reason to do functional programming. Of course, SML and O'Caml allow you to program imperatively too, since some activities are more naturally expressed that way.

    I used to be a total C cowboy, and now I love functional programming. You can just do so much more great stuff with it.

    IMO, mlton is a great compiler with which to start functional (SML) programming. The performance is incredibly good, it behaves like a real compiler from the command line, and it's free (GPL) software.

  40. The tyranny of suckage: why Ocaml is not popular by nothings · · Score: 2, Interesting
    Or maybe people don't use Ocaml due to flaws in the language and flaws in the implementation.

    Here's an example of each:

    - (language) lame support for imperative programming -- no equivalent to 'break' for loops, and even no equivalent to 'return' to allow you to return a value from the middle of a loop. Of course, imperative programming isn't the emphasis of OCaml, but it means that that "benefit" of having imperative features available when you need them isn't really quite as strong as you might like
    - (implementation) useless compiler errors -- numerous mistakes will give you the unadorned response "Syntax error", and because the language is so lacking in redundancy, mistakes can be syntactically valid for a long way, causing the syntax error to show up 20 lines later; similarly, typecheck errors themselves can be hard to decipher, since the compiler doesn't show you where the inferred types are coming from, leaving you to track them down on your own

    I base this opinion on having used Ocaml twice, working with several other programmers on IFCP entries, and from occasionaly pair programming with my officemate, who is probably the only game developer in the world using Ocaml.