Slashdot Mirror


Why Lazy Functional Programming Languages Rule

Da Massive writes "Techworld has an in-depth chat with Simon Peyton-Jones about the development of Haskell and his philosophy of do one thing, and do it well. Peyton-Jones describes his interest in lazy functional programming languages, and chats about their increasing relevance in a world with rapidly increasing multi-core CPUs and clusters. 'I think Haskell is increasingly well placed for this multi-core stuff, as I think people are increasingly going to look to languages like Haskell and say 'oh, that's where we can get some good ideas at least', whether or not it's the actual language or concrete syntax that they adopt.'"

71 of 439 comments (clear)

  1. I would have RTFA by Anonymous Coward · · Score: 5, Funny

    But I was too lazy to click on 13 pageviews.

  2. Mmmm, Kay. by jellomizer · · Score: 4, Informative

    Hascal, and other functional languages may be good for multi-core development. However not to many programmers program in them... Plus I find they do not scale well for larger application. Its good for true computing problem solving. But today most developopment is for larger application which doesn't necessarly solve problems per-say but create a tool that people can use.

    --
    If something is so important that you feel the need to post it on the internet... It probably isn't that important.
    1. Re:Mmmm, Kay. by thermian · · Score: 4, Insightful

      I spent a whole term at uni learning Miranda, which is similar to Haskell, I really liked it. I have *never* seen it being used since. To my mind they both belong in the category 'interesting, but pointless'.

      Its not just because they're old. If age was what killed languages, C and Lisp would be long dead. There just isn't anything I could do with either that I wouldn't be able to do more easily with another more 'mainstream' language.

      --
      A learning experience is one of those things that say, 'You know that thing you just did? Don't do that.' - D. Adams
    2. Re:Mmmm, Kay. by beelsebob · · Score: 4, Interesting

      I call FUD. There's a lot of things that Lazy functional languages make easy, that mainstream languages don't. Here's just a few examples:
      Infinite data structures can be handled naturally. Here's a function that generates the infinite list of fibbonacci numbers:
      fibs x y = x : (fibs y (x + y))
      Here's a list that does a complex calculation on every one of the fibbonacci numbers:
      map complexCalculation (fibs 1 1)
      While we're at it, Haskell programs are very easily parallelisable. Here's the same list, but computed on multiple cores:
      (parMap rnf) complexCalculation (fibs 1 1)
      Haskell only evaluates what it has to -- this program for example which looks up the 3000th element of the sequence will not compute the complexCalculation on the 2999 fibbonaccis before hand like a traditional program would:
      (parMap rnf) complexCalculation (fibs 1 1) !! 3000

      There's only a small sample of what's so powerful about these languages. If you'd bothered to RTFA, you'd know there are a lot more. But then, I guess this is slashdot.

    3. Re:Mmmm, Kay. by Dragonslicer · · Score: 4, Insightful

      I call FUD. There's a lot of things that Lazy functional languages make easy, that mainstream languages don't. Here's just a few examples: Infinite data structures can be handled naturally.

      Might that be because infinite data structures don't often exist in mainstream and/or commercial software applications?

    4. Re:Mmmm, Kay. by Bill,+Shooter+of+Bul · · Score: 4, Insightful

      I agree 100% Haskell is awesome. However, not everyone who is designing rails like sites is going to be working with fibbonacci numbers. We, the doers of awesome, must come up with real world solutions to real world problems that make use of the awesomeness. And then we must document the awesome for all to see and appreciate.

      --
      Well.. maybe. Or Maybe not. But Definitely not sort of.
    5. Re:Mmmm, Kay. by thermian · · Score: 4, Insightful

      It's only difficult to read if you don't know it.

      That is true of almost any language. The point is that there's nothing those languages can do that can't be done, often more easily, with the current crop of popular languages. Elegance cannot beat convenience in the workplace, or in most at any rate.

      All that aside, how many Haskell programing jobs have you seen advertised lately? Like it or not, that's what decides which languages people use.

      That's why I have to deal with languages I'd prefer to never use, because that's what pays the rent. In my own time I use C.

      --
      A learning experience is one of those things that say, 'You know that thing you just did? Don't do that.' - D. Adams
    6. Re:Mmmm, Kay. by mean+pun · · Score: 4, Insightful

      Might that be because infinite data structures don't often exist in mainstream and/or commercial software applications?

      Might that be because mainstream programming languages don't support infinite data structures?

    7. Re:Mmmm, Kay. by beelsebob · · Score: 4, Interesting

      I've seen quite a few Haskell jobs advertised recently actually, I even got one of them :).

    8. Re:Mmmm, Kay. by Dhalka226 · · Score: 4, Insightful

      I call FUD.

      I call meme misuse.

    9. Re:Mmmm, Kay. by NoNeeeed · · Score: 5, Insightful

      Here's a function that generates the infinite list of fibbonacci numbers: fibs x y = x : (fibs y (x + y))

      You have just demonstrated thermian's point.

      How often do you actually need to generate infinite sequences? I have never needed to do that outside of a functional programming class.

      I'm a big fan of alternative programming languages, I've used some 20 or so since I started 20 years ago. I did a fair amount of commercial Prolog development after I left university, I really like Prolog. It makes certain things really easy and it's a joy to code certain types of solutions in, but I'm never going to write a web-app, or a word-processor in Prolog.

      Many of these languages are very clever when it comes to doing certain things, but how often do you actually need to do those things?

      The truth is that the vast majority of the software out there does pretty dull, mostly procedural jobs. That's why the main languages in use are just dull variations on the procedural, C/Java/Perl style. No matter how much maths geeks go on about functional programming, procedural systems will always be more suited and easier to use for most of the problems out there.

      That isn't to say there is no place for these alternative languages, but it's a smaller one which you probably won't see very often.

      Paul

    10. Re:Mmmm, Kay. by beelsebob · · Score: 4, Informative

      Absolutely, and this is why there's one of freenode's biggest IRC channels, a pair of mailing lists with thousands of subscribers, and the Hackage library/tool repository just waiting to help you solve your real world problem. Be it Compiler building, version control, writing interpretters for popular imperrative languages, Writing 3D shooters, or a whole host of other tasks.

    11. Re:Mmmm, Kay. by Rob+Riggs · · Score: 3, Insightful

      Functors and generators will do the same thing for you in a more mainstream languages like C++ and Python. And they'll be a hell of a lot more understandable to your average still-wet-behind-the-ears programmer. And you can certainly write code in those languages to do lazy evaluation.

      Now, I will grant you that, in general, one can do it more concisely in Haskell than one could in C++ and even Python. But these languages are more well rounded, IMO, than Haskell.

      --
      the growth in cynicism and rebellion has not been without cause
    12. Re:Mmmm, Kay. by david.given · · Score: 4, Insightful

      Might that be because infinite data structures don't often exist in mainstream and/or commercial software applications?

      Sure they do. On my computer, there's an infinite stream of ethernet frames arriving, an infinite stream of video frames leaving, an infinite stream of keyboard events arriving, etc.

      The thing about functional languages, and strict lazy functional languages like Haskell, is that the underlying principles are quite different from procedural languages like C. In C, you tell the computer to do things. In Haskell, you tell the computer the relationships between things, and it figures out what to do all on its own.

      Personally, I suck at Haskell --- I'm too much of a procedural programmer. My mind's stuck in the rails of doing thing procedurally. But I'd very much like to learn it more, *because* it will teach me different ways of thinking about problems. If I can think of an ethernet router as a mapping between an input and output stream of packets rather than as a sequence of discrete events that get processed sequentially, then it may well encourage me to solve the problem in a some better way.

    13. Re:Mmmm, Kay. by arevos · · Score: 5, Interesting

      The point is that there's nothing those languages can do that can't be done, often more easily, with the current crop of popular languages.

      At University, I studied SML, and came out with a opinion similar to yours concerning functional languages. But when I started to learn Haskell on my own, really learn it, I found that all the concepts in my CompSci courses that seemed so pointlessly complex before, just fell neatly into place.

      I'll give you an example of a case where my solution in Haskell to a problem was rather better than any solution I came up with in C#. A while ago I was designing a program to export some hierarchical data held in a database to XML. Because SQL resultsets are 2D grids, I needed a way of converting a 2D grid into a list of fixed-depth tree structures.

      In Haskell, the solution is two lines of code, and assuming you know Haskell pretty well, it's fairly clear as well:

      listToForest :: Eq a => [[a]] -> Forest a
      listToForest = map toBranch . groupBy ((==) `on` head) . filter (/= [])
                    where toBranch = Node . (head . head) <*> (listToForest . map tail)

      I'd be interested to see if you could mirror the functionality in one of the 'popular' languages you mentioned. Perhaps something in Java?

    14. Re:Mmmm, Kay. by Dragonslicer · · Score: 3, Informative

      On my computer, there's an infinite stream of ethernet frames arriving, an infinite stream of video frames leaving, an infinite stream of keyboard events arriving, etc.

      You keep on using that word. I do not think it means what you think it means.

    15. Re:Mmmm, Kay. by grumbel · · Score: 4, Interesting

      Depends on how you determine "easy to read". The main difference between Haskel and say C is that Haskel is very dense while C is not so much, so one line of Haskel holds a lot more information then C, which of course makes look like its Haskel harder to read, since understanding a line of code requires effort, while its trivial in C. However that line of Haskel might contain the same information as a whole function in C and reading that whole function in C might turn out harder then comprehending that single line of Haskel.

      All that said, I don't consider the syntax of Haskel very good, lack of parenthesis around function arguments certainly doesn't help readability and the error messages can be rather obscure as well.

    16. Re:Mmmm, Kay. by 0xABADC0DA · · Score: 5, Insightful

      Haskell only evaluates what it has to -- this program for example which looks up the 3000th element of the sequence will not compute the complexCalculation on the 2999 fibbonaccis before hand like a traditional program would

      And then when you actually do use the other values you program is ridiculously slow because the generator function is recalculating the fibonacci number over and over again.

      Except you hope that Haskell automatically memoizes the results, but that destroys your smp performance as the CPUs contend over the result cache. So maybe you have separate caches per thread. Then you program grows larger and all the memoization takes too much memory and the system start dropping out results (3000th fib is what 520? bytes). Then you have to go back and tell it to keep the results longer for that function.

      In the end maybe you just make it a list that's precomputed.

      But that's really beside the point, because you can do the exact same thing in Smalltalk, Ruby, JavaScript, etc, with most of the same costs and benefits. So really the question is, what makes it better than Smalltalk? It's faster at maths, but that's about it. But it has a harder/alien paradigm, the syntax is foreign, etc. Maybe that's why afaik mainly Haskell is only being used by people that crunch numbers ?

    17. Re:Mmmm, Kay. by Hurricane78 · · Score: 3, Insightful

      No. It's not because of a huge lib. It's because code can be so much more generic than in other languages. And that's the biggest point/plus in Haskell. You don't have to write a new for loop for everything. Even the for loop is abstracted (map, fold, zipWith, ...). And this works with everything. I have yet to find something that's not generalizable in Haskell,

      Your 4GL claim turns out to either be true for all languages with a compiler or
      the Haskell compiler is just an abstraction you do *once* instead of reinventing it every time and using it in a crude and ugly way, like in C or similar languages,

      Your real problem with Haskell is that it is more complex per written token, and so you have to think more per token. Most people seem to generate some inner fear for things they don't understand as good as they expect. And that's the base of all your motivation to find reasons why you dislike Haskell.
      Of course you could simplify it, and get something like Python. But this is a bad idea on the long run, because then nature will only create bigger idiots. It's better to wise up a bit, because what you get then, is really really nice!

      P.S.: I once tried to design the "perfect language". I stopped as soon as I learned Haskell, because it was not only extremely similar to what I had created myself, but even much better.

      --
      Any sufficiently advanced intelligence is indistinguishable from stupidity.
    18. Re:Mmmm, Kay. by thermian · · Score: 5, Funny

      That underlying C code is what needs to be written carefully, because you use Haskell itself to write its own compiler.

      There's a Haskell compiler written in Haskell already. Where does C fit in to that?

      After the 'l' and before the 'o'.

      --
      A learning experience is one of those things that say, 'You know that thing you just did? Don't do that.' - D. Adams
    19. Re:Mmmm, Kay. by ClosedSource · · Score: 4, Interesting

      When the last argument given is "look it up", I suspect there's no counter-argument.

      In what way is there an "infinite stream of ethernet frames ariving" on your computer with its finite lifetime?

      If you have an explanation, why not give it?

    20. Re:Mmmm, Kay. by arevos · · Score: 4, Insightful

      I'm not going to take the time to look up the appropriate API calls at the moment, but I believe it's somewhere in the range of 2-3 lines of code to accomplish this feat.

      If you're not going to take the time to actually produce any code to back up your point, why bother replying?

      The biggest problem with talking about the advantages and disadvantages of programming languages is that people tend to make vague claims without producing any evidence for their case. Can JPA produce lazily produce a hierarchical tree of objects from a single database query? I don't know; it's not an answer you're likely to find in an FAQ or a tutorial. And how much work is it to actually set JPA and XStream up? Does it really only take 2-3 lines of code?

      Without providing working code, who knows whether your assertion has any merit or not.

    21. Re:Mmmm, Kay. by snoyberg · · Score: 2, Informative

      Well, in this case the "infinite stream" is really a stream of indefinite size. However, you can treat it as being infinite.

      --
      Thank God for evolution.
    22. Re:Mmmm, Kay. by Tetsujin · · Score: 2, Insightful

      Yup, lazy, functionnal, imperative, object : for each problem there is a better solution. However maybe there would be at then end a language where :

      1) syntax could be made a little less strange so that people knowing C (like python by example and then adding its own concepts) could make simple things, simply
      2) different paradigms should be coexisting peacefully - fast, simple inner loops in C, structured, object in ($dynamic language), algorithms needing such kind of concurrency or metaprogramming, possible also.

      3) a pony

      Can't help you with #3. I've been thinking about solutions to #2 (Integration between languages is still a real weak point... I hope this will change over time - part of that will be increased cooperation between the tools themselves. Seems like Microsoft has taken a decent stab at this with .NET...)

      I don't really agree with #1. I don't believe any language yet (especially not C++) has "the perfect syntax", so when it comes to defining new languages I don't believe emulation (of syntax) is necessarily the right approach. The damage done to the language as a result (syntax not matched to concepts, possible syntax innovation stifled) outweighs the benefits of familiarity. Anyway syntax has to serve the design of the language, not the other way around. Designing a language you choose priorities - what should be convenient, what should be conceptually emphasized, and try to optimize the syntax for that - and the rest winds up an inevitable compromise.

      Personally I think Haskell syntax is great. I love the foundation in format math notation, and I think the syntax fits the language. The support for extensible infix is great, and I like how this scales down to the colon operator, which is like the fundamental infix operator version of "cons"... Haskell notions of constructors (particularly them being things that can be applied or pattern-matched and stripped from data) and pattern-matching function arguments in general are a bit alien to C++ anyway, even if you wanted to try to fit Haskell into a C++-ish syntax.

      --
      Bow-ties are cool.
    23. Re:Mmmm, Kay. by grumbel · · Score: 2, Insightful

      we don't usually have wires with infinite bandwidth, disks capable of storing infinite frames of video, or users that can press infinite keys.

      You completly missed the point. An infinite data structure in a lazy language isn't something that you write down to disk or something you store in memory, its a concept with which you structure your code. For example instead of having a while-loop to poll an event from an event queue like you would do in C, you could have an infinite list of all the events that you system would ever create, but it isn't a list/array in the C sense, its much more like a generator in Python in that the elements are only generated once requested, except that you can handle it like any other list in Haskel. Having a recursive function that walks over an infinite list in a lazy language really isn't much different then having an endless loop in C.

    24. Re:Mmmm, Kay. by osgeek · · Score: 3, Insightful

      paraphrase comment #1: Haskell is too academic to be useful.

      paraphrase comment #2: No it isn't, here's how to do something with a fibbonacci sequence.

      Uh, you failed at "fibbonacci" to make your point. :)

    25. Re:Mmmm, Kay. by mdmkolbe · · Score: 3, Insightful

      Except you hope that Haskell automatically memoizes the results

      Please don't take this the wrong way, but please stop spreading your misinformation. One doesn't hope Haskell memoizes because it doesn't memoize functions. One requires that Haskell implement call-by-need. Overlapping but very different concepts. I'll assume it was an honest mistake but the difference makes the rest of your post nonsense.

      Haskell is only being used by people that crunch numbers

      Another point of dissagrement. If anything number crunchers (e.g. scientific computing in which I've done a fair bit of work) avoid Haskell (along with anything that is not Fortran, Matlab or C). Haskell finds favor more among "programing language" types who are interesting in writing their own language (Haskell is a phenominal language to wrong another language in) or in "elegant" ways to write compact solutions to traditionally verbose problems (e.g. merge sort in two "statements").

    26. Re:Mmmm, Kay. by arevos · · Score: 2, Informative

      Except nobody can read that. The line noise up there with perl!

      Nonsense. You need to be familiar with Haskell's syntax, but once you are, it's as clear as it can be for what it does.

      Reading the Haskell in evaluation order:

      filter (/= [])

      Filters out blank lists.

      groupBy ((==) `on` head)

      Groups rows whose first column is identical.

      toBranch = Node . (head . head) <*> (listToForest . map tail)

      This uses a function from Control.Applicative, but once you know that:

      (f . g <*> h) x = f (g x) (h x)

      It's not so scary. It takes the first cell from the first column of the group (head . head) to use as the value of the branch node, and then passes all the remaining columns (map tail) back into the listToForest function, and uses this as the subtree.

      Not trivial, but pretty clear when you think about it.

    27. Re:Mmmm, Kay. by arevos · · Score: 2, Insightful

      1. Start with a grid of data
      2. Filter out empty rows
      3. Group rows together that have identical values for the first column.
      4. Make a tree branch from each route, using the value of the first column as the head of the branch, and use recursion to find the child branches from the remaining columns (i.e. every column but the first) of the grid.

      So:

      A B D
      A B E
      A C F
      A C G

      Becomes:

      ......A
      ..../...\
      ...B.....C
      ../.\.../.\
      .D...E.F...G

    28. Re:Mmmm, Kay. by Pseudonym · · Score: 2, Informative

      There are several correct meanings of the word "infite". The one being used here is "unbounded".

      --
      sub f{($f)=@_;print"$f(q{$f});";}f(q{sub f{($f)=@_;print"$f(q{$f});";}f});
    29. Re:Mmmm, Kay. by tkinnun0 · · Score: 2, Informative

      Java version might look something like this:

      import java.util.*;

      class Node {
        Map<String, Node> map = new HashMap<String, Node>();

        static Node asNodes(List<List<String>> input) {
          Node nodes = new Node();
          for(List<String> row : input) {
            Node node = nodes;
            for(String column : row) {
              if(node.map.containsKey(column) == false) {
                node.map.put(column, new Node());
              }
              node = node.map.get(column);
            }
          }
          return nodes;
        }
      }

  3. Too constrained and academic by m50d · · Score: 5, Insightful
    The problem with Haskell is that it's a superb language for solving the sort of problems its designers foresaw. Unfortunately it makes it almost impossible to do things they didn't expect; you're too trapped in the rigours of the Haskell way of doing things.

    A separate, but related problem is that the community doesn't seem interested in practical use of it - there aren't lots of bindings to libraries to make easy things easy. Heck, even doing i/o at all isn't really supported very well. Functional programming is very good for the pure computer science part of programming, but unfortunately that's going to make up less than half of any given program. You also need to be able to interface.

    So I think the quote in the summary is right: people won't be adopting Haskell or similar pure-functional languages any time soon. What will happen is the next generation of dynamic languages will adopt the best features from functional programming; we've seen that happen already in python and ruby, and it'll happen again. And people will start using them there.

    --
    I am trolling
    1. Re:Too constrained and academic by beelsebob · · Score: 4, Interesting

      A separate, but related problem is that the community doesn't seem interested in practical use of it
      Really? That's why there's a new book called Real World Haskell. The IRC channel on freenode is one of the largest on the entire network, and full of people doing real world things with haskell.

      there aren't lots of bindings to libraries to make easy things easy.

      I call FUD. The Hackage databasehas literally hundreds of libraries sat there ready for you to use. And if you really need something that isn't there, the FFI is mature, and very easy to use.

    2. Re:Too constrained and academic by sribe · · Score: 4, Interesting

      You also need to be able to interface.

      Which is exactly why I find Scala to be interesting. Note: I haven't had time to learn or use it yet, but the design concept there is very interesting.

    3. Re:Too constrained and academic by Unending · · Score: 5, Interesting

      Very true, I did a large project in Haskell for a CS class once the three of us working on it hated the language after we were done.
      Before that we were pretty happy with Haskell, because the programming assignments leading up to the final project were all fitted to the language, but the instant we had to do something that wasn't, we realized what a mess it is.

    4. Re:Too constrained and academic by sergstesh · · Score: 3, Interesting

      And why not OCaml ? Nicely separated into both functional and imperative parts.

      Has a lot of lazy evaluation stuff in libraries.

      Has modifiable syntax/grammar.

      Very efficient - number 2 after "C".

    5. Re:Too constrained and academic by AKAImBatman · · Score: 4, Interesting

      No, I mean it is a true, honest to God, functional language. If you check Wikipedia, for example, you will see it listed as "Multi-paradigm: prototype-based, functional, imperative, scripting".

      See, most people look at the C-style syntax and think it means that Javascript is a C-style language. Then they get frustrated when the C-stlye code they write looks like crap. Instead, they should be coding with closures and lambda, much like they would with a LISP program. The result is a far more sophisticated program that performs more work with greater elegance than a C-style equivalent.

      I highly recommend Douglas Crockford's "The JavaScript Programming Language" introduction to the language if you're not familiar with Javascript's functional aspect.

    6. Re:Too constrained and academic by AKAImBatman · · Score: 3, Informative

      There's a more in-depth article on Javascript's functional capabilities here:

      http://www.hunlock.com/blogs/Functional_Javascript

      Other stuff I pulled out of Google for your perusing:

      http://dankogai.typepad.com/blog/2006/03/lambda_calculus.html
      http://math.ucr.edu/~mike/lc2js.html
      http://www.joelonsoftware.com/items/2006/08/01.html
      http://www.ibm.com/developerworks/java/library/wa-javascript.html

      What this all means is that Javascript is the most widely deployed functional language in existence! And that's a fact you can take to the bank.

    7. Re:Too constrained and academic by cylence · · Score: 2, Interesting

      This is only true for specific implementations. The Haskell 98 report only specifies library support for textual input/output, and is completely useless for portably handling Binary IO. That everyone just uses GHC anyway, which has great support for Binary IO, doesn't negate the point that Haskell itself sucks when it comes to IO.

      Other serious shortcomings would have to include lack of proper locale/encoding support (characters are read in as Unicode values; but what is the original encoding assumed to be, then? Current implementations do byte-for-byte, which also isn't great), and lack of serious exception-handling (though that is probably mitigated considerably by the Maybe monad in combination with "do").

      Haskell is a gorgeous language, but it does have some serious shortcomings, at least when it comes to the official specification as opposed to popular implementations. GHC has done much in making it a truly useful language, and so most people mean GHC when they say "Haskell". Which is plenty portable enough, I guess, considering that it is capable of using GCC as the compiler backend.

    8. Re:Too constrained and academic by raddan · · Score: 3, Insightful

      I think the real problem with Haskell is that you're required to use your brain to make any use of it. I.e., you have to be one of those people who, upon opening a Knuth book, goes "Wow!" If you were a mediocre CS student, or you have no formal CS or mathematics training, Haskell is going to be very hard for you to wrap your head around.

    9. Re:Too constrained and academic by cylence · · Score: 2, Insightful

      That a language has "functional aspects" doesn't make the language itself "functional". By the same reasoning you use, Python is a "functional language" too. Hell, even Perl has closures and lambda. And Python has list comprehensions and such. Pretty much every high-level language has these things; that doesn't make them functional.

    10. Re:Too constrained and academic by AKAImBatman · · Score: 2, Informative

      What would you describe as "Functional" then? i.e. What is the key difference between a Functional language and a language that has "Functional Aspects"? Show me the difference you believe is there and I'll show you the Javascript goods.

      Oh, and BTW? Academia agrees with me that Javascript is a functional language.

      Javascript is a functional language [...] The world's most-widely deployed functional language
      --Professor of Theoretical Computer Science Philip Wadler, University of Edinburgh

    11. Re:Too constrained and academic by BotnetZombie · · Score: 2, Interesting

      If you don't know of it already, you might also wanna take a look at Clojure, a Lisp dialect that can either be interpreted or precompiled to .class files.

    12. Re:Too constrained and academic by NoOneInParticular · · Score: 4, Interesting
      A pure functional language would be a language where there are no side effects. I.e., you can't change the state of anything, you can only construct new things out of existing things. As this gives some problems with IO, Haskell, taking purity to the extreme, had to wait for the invention of Monads to be able to do IO. Yes, Haskell was not capable of IO (reading/writing) for years. Functional languages follow this pattern: side-effects are only permitted if there is no other way. Examples are Lisp and Scheme, but also Matlab, Mathematica and Scala. Other languages allow side-effects by default, and have functional aspects in other respects. Examples of these are Javascript, Ruby, Python, Java, C++, C and even assembler (programming without any functional aspects is going to be hard). Quite likely Javascript programming can be done almost purely functionally. But so can C.

      So, if you can show me that you can't have mutable variables in Javascript, we can call it functional.

    13. Re:Too constrained and academic by AKAImBatman · · Score: 3, Interesting

      An excellent post, sir. Much more on target than cylence's attempts.

      A pure functional language would be a language where there are no side effects.

      This is correct. However, I did not claim that Javascript is a *pure* functional language, only that it is a functional language. If we go by the definition of a pure functional language, then we must discount a long list of functional languages as well. That includes the poster-child for functional programming: LISP

      Javascript allows for pure functional programming just like any other functional language. However, it does not enforce the purity of functional code. Something that is a very difficult goal to reach. This combined with the C-Style of the language has the negative effect of encouraging imperative programming. With suitably predictable results. (How many times have we heard, "Javascript sucks!")

      This is why I often refer to Javascript as a "LISP-style functional language". The two don't line up exactly, but the foundations of Functional List Processing are present in both.

      An interesting aspect of the language's real-world use is that the designers of Javascript's web APIs could have created APIs that force imperative thinking. Yet they didn't. Even for traditionally imperative operations (e.g. networking), the designers of Javascript's web APIs have seen fit to ensure its functional nature through the use of an event system. e.g. I do not read values from XMLHttpRequest, I wait for a functional call.

      I personally think it's fascinating that the functional underpinnings of the language have been so well preserved despite the lack of general knowledge about the language. The efforts they are putting into the language will pave the way for more mainstream functional languages in the future.

  4. Why they don't rule: by Kingrames · · Score: 5, Funny

    The picture in the linked article is missing a beard.

    --
    If you can read this, I forgot to post anonymously.
    1. Re:Why they don't rule: by Bob-taro · · Score: 5, Informative

      The picture in the linked article is missing a beard.

      I was going to mod you funny, then I thought maybe a lot of people wouldn't get the beard reference, so I decided to post instead. Anyone else want to mod parent funny?

      --
      Prov 9:8 Do not rebuke mockers or they will hate you; rebuke the wise and they will love you.
    2. Re:Why they don't rule: by solraith · · Score: 2, Funny

      Way to take one for the team!

    3. Re:Why they don't rule: by moderatorrater · · Score: 4, Funny

      Anyone else want to mod parent funny?

      Yes, I will!

      Oh crap.

  5. It's not for dumb people by OrangeTide · · Score: 4, Insightful

    I haven't really been able to figure out how to do anything significant in Haskell. But I suspect that one day a language more like haskell and less like C will end up being the most popular. Monads and all that kind of confuses me.

    I think it helps if you have a strong math background and are comfortable with Lambda calculus. I'm just an old C hacker and haven't used any real math in like 10 years, so I'm not that effective in Haskell :(

    --
    “Common sense is not so common.” — Voltaire
    1. Re:It's not for dumb people by LWATCDR · · Score: 4, Funny

      Don't worry.
      In a few years you will see c++++ which will be c++ with functional programing tacked on. Of course you will also see Functional Object C but only Apple will use that.

      --
      See my blog http://ilovecookes.blogspot.com/ for light hearted technical information.
    2. Re:It's not for dumb people by Abcd1234 · · Score: 3, Interesting

      People will get more intelligent just by using functional languages.

      Don't be ridiculous. Functional vs procedural isn't a matter of intelligence. It's simply a way of thinking. And the reality is that procedural languages better match the way the human mind works.

      IMHO, learning to program in a functional style is like a right-handed person learning to write with their left. Yeah, they can do it, but it requires a ton of work for dubious real-world benefit, and in the end, it's never really natural, simply because that's not the way the brain is wired (except for the odd freakish exception ;).

    3. Re:It's not for dumb people by the_greywolf · · Score: 2, Insightful

      Well, that C++0x thing or however its called has lambdas and functions closer to being a first class construct...so thats pretty much exactly whats happening already, give or take :)

      Have you looked at the syntax? You're basically just binding functions together in template parameters, then invoking them. Normally, I'd be pleased as punch that it's being included but... DAMN is it ugly syntax.

      --
      grey wolf
      LET FORTRAN DIE!
    4. Re:It's not for dumb people by beelsebob · · Score: 2, Insightful

      And the reality is that procedural languages better match the way the human mind works.
      To quote you -- don't be ridiculous. From my personal experience of teaching people functional programming, it's nothing to do with imperative programming matching the brain better. Instead, it's to do with people learning to write imperative programs first, and then having a very steep unlearning curve to deal with at the same time as the learning curve for functional programming.

    5. Re:It's not for dumb people by DragonWriter · · Score: 2, Insightful

      And the reality is that procedural languages better match the way the human mind works.

      I don't think there is any evidence that procedural languages are easier to understand; SQL, which (like functional languages) is declarative rather than procedural seems to be at least as simple as most programming languages for even neophytes to understand.

      Procedural programming is probably easier to understand if you started out for years learning procedural languages, or if you come from a hardware-centric background; OTOH, if your first experience with computer programming is spending years exclusively with functional languages, or you come to programming with a background heavy in math and formal logic, functional programming is probably fairly easy.

    6. Re:It's not for dumb people by TuringTest · · Score: 2, Insightful

      And the reality is that procedural languages better match the way the trained programmers mind works.

      There, fixed for you.

      There's nothing natural in the "change-one-byte-at-a-time" von-Neumann bottleneck languages, other than they're the ones taught in standard programming courses.

      Oh, you mean that the human mind keeps track for changes of state in the environment? Sorry to break the news to you, but that can also be done in functional languages.

      --
      Singularity: a belief in the "God" idea with the "demiurge" relation inverted.
    7. Re:It's not for dumb people by TuringTest · · Score: 2, Insightful

      As for an "instance of a normal, everyday situation in which humans use a functional model of computation":

      SELECT Name, Age FROM My_country
      WHERE Age > 18
      GROUP BY Age

      You'd be hard pressed to find someone thinking of the age groups in their country using a "for..next" model.

      --
      Singularity: a belief in the "God" idea with the "demiurge" relation inverted.
  6. Re:Why "lazy"? by tuffy · · Score: 5, Informative

    They're "lazy" because they don't do any work until necessary. For example, a function can return an infinitely long list, but only the elements you request will actually be calculated. Or, to compare them to Python, it's like having everything function like an iterator.

    --

    Ita erat quando hic adveni.

  7. one of the best practices by fermion · · Score: 2, Interesting
    At least since the late 70's, and certainly through the 80's, one of the best practices was functions that had limited scope and data knowledge. Of course this was codified into OO languages, but even in old style languages it was always bad to know too much or make too many assumptions about what was going on elsewhere.

    We can see this philosophy in C where, except where huge data structures are involved, it is best to make a copy of data rather than work to work on someone else's copy. Likewise functions do one thing, do it well, and, again except for huge data structures, return a copy. Memory is manually allocated, and deallocated, possibly from the functions local heap.

    It is interesting to me how it all comes back to just best practices. Make sure you know how much memory you need. Make sure you are only doing what needs to be done right now. Make sure the interfaces are clear. If data is ready, then it should be ok to work on it. To me functional programming is what happens after data models, or objects, are defined. Once the data structure is defined, you can treat it as stateless immutable input. Output is a another structure. Again, the only limitation is if the object is so large that duplicating become a cost performance issue.

    --
    "She's a scientist and a lesbian. She's not going to let it slide." Orphan Black
  8. Lazy Functional vs Lisp? by rolfwind · · Score: 2

    What's the difference between a functional language like Lisp and a lazy functional language?

    Just asking.

    1. Re:Lazy Functional vs Lisp? by clampolo · · Score: 2, Interesting

      Lazy evaluation means that a value won't be calculated until it is absolutely necessary. So in the example in the above discussion, you can make things like an array of all the Fibonacci numbers. This works because the environment won't actually calculate anything until it is necessary.

      Lisp doesn't support this behavior by default. In LISP all function arguments are evaluated left to right. Although using macros, you could probably write your own lazy evaluation mechanism.

    2. Re:Lazy Functional vs Lisp? by mdmkolbe · · Score: 3, Interesting

      In a lazy language (more properly called "call-by-need"), every expression has a thunk wrapped around it and thunks are automatically forced. (They have thunks in Lisp/Scheme but they must be explicit rather than implicit.)

      Lazy languages allow you to "use" values that haven't been defined yet. For example

      a = 1 : b
      b = 2 : a

      Which would produce two lists of alternating ones and twos (a starts with 1 and b starts with 2; also ":" is infix "cons").

      In Scheme (which I know better than Lisp), you could accomplish the same with

      (let ( [a (cons 1 #f)]
      [b (cons 2 #f)])
      (set-cdr! a b)
      (set-cdr! b a)
      ...)

      But being lazy (1) frees you from thinking about order of evaluation and (2) allows some constructs to be expressed more easily (e.g. taking the fixed point of a composition of functions (example to complicated to post here)).

      At the end of the day, any program written in one style can be written in the other so its all differences of ease and different ways of thinking about the program.

  9. Oh my god! by Vexorian · · Score: 3, Funny

    Could this be the year of Haskell in the developer's tool box?

    --

    Copyright infringement is "piracy" in the same way DRM is "consumer rape"
  10. Combinatorial Parsers, etc. by Tetsujin · · Score: 2, Interesting

    One thing in Haskell that always intrigued me was the idea of combinatorial parsers - a parser that accepts a string and yields not a single parse tree, but all possible parse trees based on the language rules... Simple implementations of those can be implemented in Haskell pretty straightforwardly. Combinatorial parsers for individual rules are stuck together - and while rules may generate a bunch of possible parse trees these are culled by successive rules...

    I don't know too much about the practical efficiency of these - but in terms of how they're expressed I think they're great...

    --
    Bow-ties are cool.
  11. The lazy language by jd · · Score: 2, Funny

    ...is the one with the newspaper over its face, snoring in the corner, cans of soda piled up on the desk. The functional language is the one that has finished psychotherapy, is fully alert and active, and has a far higher risk of suffering a heart attack from overwork.

    --
    It's a small world and it smells funny; I'd buy another if it wasn't for the money; Take back what I paid (SoM)
  12. Arrrr, it's Stephenson again! by Mr.+Underbridge · · Score: 2, Funny

    I haven't really been able to figure out how to do anything significant in Haskell. But I suspect that one day a language more like haskell and less like C will end up being the most popular. Monads and all that kind of confuses me.I think it helps if you have a strong math background and are comfortable with Lambda calculus.

    Monads, lambda, calculs...arrr, matey, now I know why Haskell's such a bloody mess - Neal Stephenson wrote it! That be why it seems good at first and falls apart at the end.

  13. Re:Why "lazy"? by mgiuca · · Score: 2, Insightful

    Now, if Haskell is smart enough to be able to cache the result of the 100th Fibonacci number and use it later (like as the starting point for the calculation of the 200th), that would be useful.

    Well Haskell isn't "smart" in the sense that it goes out and arbitrarily caches things it thinks may be helpful (that way leads to madness).

    It does cache computations it's made if you store them in a variable or part of a data structure, so if you plan things right, you can get the behaviour you want.

    Basically, here's one advanced way of calculating fibs in Haskell:

    fibs = 0 : 1 : [ a + b | (a, b) <- zip fibs (tail fibs)]

    (From Haskell for C Programmers).

    This takes a bit of thinking to work out, but basically it declares fibs as a list of ints, which is infinitely long, the first two elements are 0 and 1, and each subsequent element is the sum of the previous two.

    But there's a catch - unlike C where declaring an infinite data structure would be absurd, Haskell stores it this way:

    [0, 1, <some vague concept of the remaining computation>] - a finite data structure of in fact just three elements.

    Now you request the 100th fibonacci number, like this: (fibs !! 99). Haskell doesn't know the value of elements 2 through 99, so it unrolls it, performing the computation as much as possible - that's the laziness. Now it stores:

    [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ... , 218922995834555169026, <some vague concept of the remaining computation>]

    And it returns you the value 218922995834555169026 which is the last *known* element of the list. Note however that the computed list so far remains.

    Now you request the 200th fibonacci number, like this: (fibs !! 199). And Haskell figures it has to do some more computation, but it already knows the first 100. So it just unrolls the next 100 elements, and gives you the 200th fib. You could subsequently request (fibs !! 37) and it would look it up without recomputing.

    Note that this is a bit of a bad example, as Haskell uses linked lists, the lookup itself is linear, which is the same as the computation time. But other more expensive computations could be done using this technique.

    Also note that my definition is a lot smaller and closer to the mathematical definition of Fibonacci sequence than your C code. Functional programming is (or at least tries to be) about defining what you want to compute, not how you want to compute it. Having said that, it does often mess with my head and I tend to use imperative languages for this reason ;)

  14. How is X better than Y? by Tetsujin · · Score: 3, Informative

    Actually, when you're able to do it naturally in your language, it becomes a very useful thing to do. For example, when you want fresh variables in a compiler

    How is that better than doing (or basically the same in Java/C/perl/ruby/etc.):

    __compiler_var_num = 0
    def next_fresh_variable():
      global __compiler_var_num
      __compiler_var_num += 1
      return "_id_%d" % __compiler_var_num

    I hate to say "you're missing the point" because I feel that's unreasonably dismissive - though I kind of feel you are...

    IMO the point isn't necessarily that one method is "better" than another - it's that this idea represents an important and useful way of approaching programming problems. If you understand the style you can appropriate it - it becomes a useful concept for expressing problems and their solutions.

    So for instance - while you may not use recursion in C for general problem solving (due to the lack of tail-recursion optimizations which turn the thing into a loop) - understanding the recursive expression of a problem is useful for structuring your solutions, understanding what assertions must be made with respect to the state of the data at what points in the code, etc. - even if you structure your solution as a loop rather than a recursion.

    And it should be noted that you can implement infinite sequences in C++, etc. - generally the way to do this is with iterators, and the use case would be for feeding those iterators to algorithms that expect iterators... What Haskell brings to the table is that it encourages you to think of problems and solutions in those terms - learn the method and what you can do with it, how it affects the expression of your code - if you find it a useful idea it's easy enough to implement in most object-oriented languages...

    --
    Bow-ties are cool.
  15. quantification of productivity by j1m+5n0w · · Score: 2, Insightful

    The same way they should measure the productivity of any team of programmers: are they able to solve the problem they're given within time and budget constraints. "Lines of code" is not a good measure of productivity in any language.

  16. Transactional Memory by wirelessbuzzers · · Score: 2, Informative

    Thoughts on Haskell, from a Haskell programmer.

    Haskell has a very nice software transactional memory library, which makes a lot of otherwise-difficult concurrency problems much easier. It's statically safe, too, unlike similar libraries for imperative/OO languages.

    Certain other language features are very nice. Monads are also extremely powerful once you wrap your head around them, and the type-class system and standard libraries make a lot of math programming problems much easier.

    The language also has downsides. The laziness makes it possible to build up an arbitrarily long chain of suspended computations, which amounts to a hidden memory leak. Laziness also complicates the semantics for "unchecked" exceptions, most notably division by zero. The combination of laziness and purity can make the language very difficult to debug and optimize. While the compiler has very powerful optimization capabilities, sometimes code needs to be just so to use them (like flagging things "const" or "restrict" in C), and this can make it hard to write clean code that runs fast.

    The other problem is that most programs need some amount of imperative code somewhere to do the I/O. This code has a tendency to be verbose, nasty and slow in Haskell.

    There are also some problems that would be relatively easy to solve in a very nice way within the semantics of the language (give or take), but are not solved well in the standard libraries. These include exception handling, global mutable state, strings and regular expressions, certain I/O operations, arrays and references. It would be very nice if the ST and IO monads were unified, and if references and arrays had nice syntax; this would reduce the ugliness needed to write those occasional bits of imperative code.

    --
    I hereby place the above post in the public domain.
  17. visibility of hackage by j1m+5n0w · · Score: 3, Insightful

    I've never heard of Hackage until I read this post, even though I've been reading about Haskell and other functional languages on and off for several years now.

    Hackage is well known to haskell programmers. It is linked to directly from the front page of haskell.org, it is mentioned frequently on the haskell-cafe mailing list, and that's where hundreds of haskell projects are hosted. If you're an average passer-by and not an active haskell developer, it's not necessarily going to jump out and say "boo!", but it isn't hiding under a rock, either.

    Note: hackage is not the standard libraries. Those are documented elsewhere.