Purely Functional Data Structures
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.
Good thing they left 300 yers ago then.
As opposed to what, Data Structures that don't work? Yeah, we need more books on those...
Management prefers dysfunctional programming.
blonde... brunette..
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?
Is 'OCaml' pronounced 'Oh-Camel', 'Ach-amel'...? Akin to the 'Line-Ux' versus 'Lin-Ux' confusion.
I recommend Thin Client's and Fat Fiber!
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?"
You know, your computer is not a typewriter, so you really could have rewritten that part of your review...
that supports GOTOs. Those are the best!
Next thing we know, people will start reading the books as well!
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.
article... triggering... college... flashbacks.
..must.. resist...
..cannot.. fight.. functional
..language.. tempatation...
*head explodes*
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.
4.1.8. PureFun
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.
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
So, functional programmers, how to improve such a program without simply mimicking the imperative version?
Slashdot ate my spaces.The ocean parts and the meteors come down
Laid out in amber, baby.
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.
Engineering and the Ultimate
... I prefer COME_FROM.
Microsoft Excel is a functional programming language. Discuss.
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.
Engineering and the Ultimate
"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
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?
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.
But people like it.
Typing like you talk--well, if you talk flowingly--typing how you talk makes (people hate this about me) it makes it more conversational.
tasks(723) drafts(105) languages(484) examples(29106)
My understanding was that, in general, the "efficency" of laziness is outweighed by the cost of the bookkeeping for it. After all, a function uses the parameters it is passed most of the time.
I'm a fan of functional programming, but lazy evaluation complicates the code and slows it down. That's one advantage of scheme's function-calling semantics over lisp's, IIRC (can anyone confirm?).
-1, Too Many Layers Of Abstraction
I'm learning lisp at the univeristy right now, it's really another world, upside down and inside out, for me who's used to c/c++ =)
Heaps:
Trees:
Queues:
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
"But I'm getting ahead of myself, because I haven't described what a functional language is, or why it is useful"
I seached monster dot com for lisp and got 12 hits, so clearly there's a use for it.
So this is what computer programmers do in their spare time - program computers! WooHoo!
-----
Sorry, I'm only a 1336 h4x0r.
Did the mods miss it? It's not exactly offtopic, if you get the context right. The line was from somebody examining DATA STRUCTURES representing people in the "Matrix", remarking that after a certain period of time, he stopped classifying them conciously and started seeing "blond, brunette".
I suppose he is implying that this book would be of no use to him.
Is that enough explanation? Jesus Christ.
THIS THING CAN TURN ON A DIME, MACROSSZERO STYLE ALSO FUCK BETA, ~NYORON
...that you can design data structures that parallel the way in which you represent numbers? You mean like this?
Doesn't it make you feel good to know that our freedoms are protected by politicans, lawyers and journalists.
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.
Really. Try this one: http://www.nomaware.com/monads/html/index.html
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
The tool for manipulating this new IL (ILX) is F#, an ML family functional language. This is because ILX fits more naturally with a functional language than it would with, say, C# or C++.
C# and the like can still be used, but if you look at the ILX and compare it to F#, the reason for using a functionl language should be obvious.
I don't know if you can do this with Java or not, but if there were such a decompliler, the output would be much easier to work with as in ML than with Java itself.
This one. It runs pretty fast, though it can take quite a while to compile...
I'm trying to teach myself to set people on fire with my mind... Is it hot in here?
Functional Programming sounds to me as Pascal put upside down: ..
Pascal Doesn't let the coder make mistakes.
This lets the coders make mistakes, and just ignore those
This may sound ok, but it helps you create big nasty bugs that will go unnoticed until they popup and ruins your life.
It's actually easier to debug such things in languages like C or ASM.(Not only easier to debug, but also harder to create such a monster)
WTF am I doing replying to an AC at 5 A.M on a Friday night?
I've been programming for a while now. Spent quite a bit of time coding in C, enough to wire the imperative model happily into my brain. I learned and programmed in other languages as well - mostly imperative - including Fortran, various assemblers, smalltalk, algol, apl, C++, perl, python, java ....
And then I learned Haskell. Haskell is one of the simplest languages around, and it can be great fun to use as well. If you want complicated, try C++ or java or perl.
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.
It took OOP nearly 30 years to catch on for good. It took garbage collection nearly 40 years to become widely accepted.
The industry will come around to functional programming eventually: OOP simply isn't up to the task of building large systems that are also reliable and robust. FP is much better at that. I don't know how many more failed space probes, software disasters, and power outages it will take before people catch on to that fact, but it will happen.
Yup, I'm an academic - but I've also done real programming. Learning the functional programming mindset took some time, and learning to really program in functional languages (I like Haskell as it makes it hard to program non-functionally) took some serious work. I can pick up most algol family/imperative languages in a couple of days, at least enough to feel comfortable and be able to code real problems. Haskell took more than a month to master (maybe about a week to get the basics) but then it finally really clicked (and I suspect the click was probably audible, it was so sudden and revelatory). And my program analysis skills and my programming skills have been all the stronger since.
Okasaki's book not only helped me understand the functional programming model, it helped convince me that there was more to it than just fun languages.
I recommend this book highly for those who are interested in functional programming, or who are interested in learning more about data structures and algorithms on many levels.
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.
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
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/
http://www.cs.uu.nl/people/jeroen/article/jpeg/
A good example of how terse yet powerful functional code can be: JPEG decoding in a few pages of code. Damn.
--Dan
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.
http://dada.perl.it/shootout/
It's worth noting that PLT Scheme has a really powerful "object" system, that's a lot more powerful than javas. It lets you do structures, objects, classes, interfaces, modules, units, and boxing. These things help get around the insufficiencies of objects. Oh, and they're all (except modules) first class objects.
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.
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.
Table-ized A.I.
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
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
I had no idea such a book existed. Thanks.
gene
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?
http://www.merjis.com/developers/
Rich.
libguestfs - tools for accessing and modifying virtual machine disk images
Just thought I'd post a link to an example of an imperative language implementing JPEG decoding in only a few pages of code. :-).
-Billy
I downloaded the book. However, at 160 pages it seems a little intimidating. I'm not a real programmer, I just code. What I had in mind was something akin to a 2 to 10 page (max) tutorial that would help me learn about it, and then I could apply it to my Perl code.
I did something like this before, there was a 2 page tutorial on the net that showed functional programming for perl. It showed you various techniques like passing functions into functions and making compound functions. Stuff like that has come in handy.
So, at the moment I've written stuff to generate user interfaces and databases given a description of how they should look like (using XML). I'm wondering how I can move beyond using arrays, hashes, and objects in Perl. The article sounds like there might be something that the Functional people have figured out about writing application logic and user interface Models (as in the M of MVC) that I can steal from. Is this true?
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.
If if had any merit, Microsoft would have already stolen it, or SCO would be suing Curry for IP infringement. Nice try - back to work people.
boycott slashdot February 10th - 17th check out: altSlashdot.org
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.
Crystal Reports is also a sort of functional system (though I've abused the hell out of its imperative capabilities, mostly to make up for lack of programming tools at other levels).
I search the page for the word in it wasn't ther
so here it goes:
In the white paper I read about functional
languages there is a strong emphasis on coding
an algorighm and showing it's correctness or
proof. In today's arena we programmers gauge
ourselves by our abilities debugging code. Bugs
are a given. We like to believe that debugging
thousand lines of code is a small price to pay
for the wonders of procedural language.
Hard to quantify I must admit but for those who
compare Haskell or other functional language against
any procedural language please remember the
issue of correctness.
Because even if is cheaper and faster to count
cows by counting the legs and dividing them
by four...still wrong.
- these are not the droids you are looking for -
Since c++ template metaprogramming seems to be the most widely used "functional programming language" in use today, wouldn't there be a market for re-writing many functional programming books using c++ template metaprogramming techniques. (Structure and Interpretation of Computer Programs, The Little Schemer, The Seasoned Schemer)? Any comments?
that supports GOTOs. Of the computed sort.
I'll have to check this out.
Anyone who wants to learn ML and the principles of functional programming could do a lot worse than getting a copy of Larry Paulson's "ML For The Working Programmer"
There's a nice compendium of qualitative comparisons of O'Caml to other languages (Java/C/C++/Ruby/etc) here
O(n*log(log(n))) steps to find the primes out to n. If you want the first n primes, add in another factor of log(n) to account for the density of primes.
/. breaking a line in a bad place):
The sieving involves one action every time a prime divides a composite number (ie strike out that composite number). Since the average number of prime factors averages out to log(log(n)), the number of actions is just barely supralinear.
In reality, of course, if you don't want to accept artificial limits, you will hit the fact that just talking about very large numbers gets more difficult since the representation has to get larger than any convenient fixed size representation. Throw in another log(n) if your code handles large integers.
I don't know if any purely functional implementation can approach this performance level. The basic action of "striking out" involves modifying a value in place. Recopying the modified datastructure is problematic since the datastructure is large. Incrementally layering changes is likewise problematic since upon access you have to search your incremental changes - most of which do not apply to the number you are looking up.
Here are 2 implementations in Perl. One uses closures heavily (but isn't really functional since it uses assignment) while the other is very, very short. For amusement here is the short implementation (made longer by one space to avoid
sub sieve {
grep{@_[map$a*$_,$_..@_/($a=$_)]=0if$_[$_]>1} @_=0..pop
}
print join " ", sieve(100);
It scales like the C version does, albeit with far worse constants. Other than practical memory issues, there are no limits on how big a list this can handle.
Dude. What you are writing is a troll itself.
Comp Sci is generally IS a programming degree. Computer Information System Degrees are a different branch of the I.T. sector.
Usually one can cross from either side if you have enough work exprience BUT for a MASTERS degree (in either) you take courses pertaining to the other side.
(e.g. Developers/Programmers "C.S." and System Admins/Network Admins "C.I.S.")
Until you define PRIME as the act of determining whether or not a given number is prime.
And by P in this case, we mean polynomial in the number of bits that you need to represent the number. In other words the standard solution of "trial division up to square-root n" is an exponential solution.
I wish you better luck the next time that you try to quote a result that you don't really remember and didn't understand.
nothings wrote:
>
> 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
This is false.
OCaml can raise exceptions, which will do exactly what you want.
> useless compiler errors -- numerous mistakes will give you the unadorned response "Syntax
> error"
Try running your code through the preprocessor (add "-pp camlp4o") and your "Syntax error" turns in to, for example:
File "foo.ml", line 8, characters 4-6:
Parse error: ':>' or ':' or ')' expected after [expr] (in [expr])
Preprocessor error
make: *** [foo.cmo] Error 2
I do wish people would take the trouble to actually learn the language before posting ignorant and derogatory criticisms like the one in this post. Your errors could easily have been corrected by reading the manual and/or looking through a FAQ. You're also welcome to ask questions on the OCaml mailing list, the OCaml Beginners Yahoo group, and #ocaml on freenode.
Cheers!
So after literally WEEKS battling with this show-stopping bug, it took him a couple of hours to find the code, identify the bug and implement a work-around in his code...
Q.
Insert Signature Here
This is virtually never a problem in practice. Syntax highlighting in your editor gets you 99% of the way there. And when I can't immediately see the source of a syntax error I simply hit "u", the undo key in vim and I can see what I did to cause the syntax error in the first place (usually an ommited semicolon). The Code a little... test a little methodology does wonders for this sort of thing, and any reasonably experienced programmer should be using it anyway.
I only wish that I could use OCaml in my projects. Unfortunately, on 32-bit architectures (read: x86), OCaml native arrays can contain no more than 2^22 elements.
However, if you tend to work with arrays containing 10M elements or more, OCaml just is not an option. (BigArray is not an option unless your data are all numerical.)
Sadly, this restriction rules out the use of OCaml in large-data settings, i.e. most numerical and scientific computing.
Does SML have array size restrictions?
OCaml supports functional, imperative and object oriented paradigms, is much more widely used, and therefore has many more libraries and applications written in it and for it. No that Scala doesn't have potential, but if you're looking for something practical use OCaml.
You forgot a couple more:
* Total lack of ad-hoc polymorphism. This language has such a problem with overloading, you need a different operator for adding floats than you do for adding ints.
* Supposedly awesome module functor calculus that fails to show up with any useful examples in the standard library -- for data structures, you tend to call a lot of static functions in modules that are, you guessed it, non-polymorphic.
* Lack of compiler warnings. My all time favorite error in ocaml goes like "The value is declared type Foo, but is used here with type Foo". It will drive you insane when developing via ocaml-mode in emacs, because it doesn't do a fresh recompile, so you end up redefining types and the compiler doesn't make a peep of warning. I learned to stick with makefiles when developing, to preserve my sanity.
As a better C, ocaml looks great. But it fails to offer many credible alternatives to what even ugly old C++ offers in ad-hoc and parametric polymorphism.
I've finally had it: until slashdot gets article moderation, I am not coming back.
Genamics lists 989 journals related to Computer and Information Sciences. Surely some of them are good.
How about the Journal of Functional Programming or Theoretical Computer Science, or perhaps the Journal of Algorithms. And, for a more general approach, there's always the Journal of the ACM.
I haven't read any of these extensively, but surely some of them will have the kind of articles you'll enjoy.
srytch wrote:
;;
;; ;;
>
> Total lack of ad-hoc polymorphism. This language has such a problem with overloading,
> you need a different operator for adding floats than you do for adding ints.
This is a Good Thing (TM). That means that your language isn't going to do implicit conversions from floats to ints (or vice-versa) behind your back. This was an explicit design decision, due to the recognition that the programmer is smarter than the compiler. You are the programmer so you should decide how types are converted from one type to the other, not the compiler. Of course, if you want, and only if you want, you can easily create a composite type and a library of functions that will do all of the conversions for you. Curiously no one has seen the need to implement such a library.
> Lack of compiler warnings. My all time favorite error in ocaml goes like
> "The value is declared type Foo, but is used here with type Foo".
This is covered as the first question in the OCaml FAQ, and personally I have run in to that situation exactly once in my entire experience programming OCaml. So I consider this particular error message a relatively rare corner case... certainly nothing to condemn a whole language over.
> As a better C, ocaml looks great. But it fails to offer many credible alternatives to what
> even ugly old C++ offers in ad- hoc and parametric polymorphism.
Don't even get me started on C++. Instead, start by reading this. C++ is not even in the same league as your average functional programming language, much less OCaml.
Second, ocaml has parametric polymorphism. Read this. And this... google for more. And here's an example of OCaml's parametric polymorphism:
# let f x = x
val f : 'a -> 'a = <fun>
This creates a parametrically polymorphic function, named "f". And here is how you would use it:
# f 3.14159
- : float = 3.14159
# f "0wn3d"
- : string = "0wn3d"
Back here you said, PRIME (aka, finding all the primes) is not greater than n (aka, linear). Which made perfect sense in context since the sieve that was under discussion finds all of the primes.
However, as you agree just above, that isn't the definition of PRIME.
Which means that, in addition to getting the efficiency of the algorithm wrong, you got the definition of PRIME wrong.
I'm an electrical engineer, so it's not surprising that there's a lot of computer science that I don't know about, but this is literally the first I have heard about functional programming, and suddenly all these people are replying saying they've read the book, or do such programming at work... I feel like I've missed something.
For you people who use this, or say it is used at your work: for what is it used, and why this versus any other language?
I use C/C++, Java, Perl, and various types of microcontroller assembly, and lately I've been wondering if I should learn Python or Ruby. Now here's another can of worms.
I have found that learning a computer language introduces me to new mental constructs, different ways of representing information that can often be applied outside of coding... so I guess what I really want to know is: what languages should I, as an engineer, know to be able to communicate effectively with programmers?
I realize the question is broad and open to interpretation, but if anyone has recommendations I would be most grateful.
This is a Good Thing (TM). That means that your language isn't going to do implicit conversions from floats to ints (or vice-versa) behind your back.
Ad-hoc polymorhism / overloading does not imply implicit conversions.
A bunch of the prominent people in the FP community work for Microsoft in England.
Just out of curiosity, since I know and use SML but have only heard of Ocaml: what're the relative strengths? Is there a reason for me to learn Ocaml as well? I gather that they're both derived from the original ML, and share a lot of features, but I was wondering whether I ought to care about Ocaml or just stick with SML (since I already know it).
10 PRINT CHR$(205.5+RND(1)); : GOTO 10
If you're looking for really earthshattering ideas that every computer scientist would know, like, say, the idea of reducibility to NP-complete problems, I'm not aware of any recent ones. But if you're willing to go for more narrowly-applicable ones, there's a bunch. There's been a few new transforms in the last five or so years that have been applied to audio compression, though many are just variants on older ones, so maybe aren't "really" new. Machine learning has a bunch of stuff as well: support vector machines were invented in 1998 I think, to pick one example.
10 PRINT CHR$(205.5+RND(1)); : GOTO 10
Well, you might not be any good at complexity theory, but that's hardly the same thing. Computer science is a broad subject, and anyone who can tell me in 2004 that "computer science" is just a narrow mathematical specialisation is academic in every sense of the word.
(And yes, I do have an academic background in CS, and yes, I can prove the standard limit on sorting.)
No, that's academia, which is not at all the same thing.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
"Hey they're not warts, they're beauty marks". Funny how it becomes a Good Thing in one's Favorite Pet Language. I'm not talking about MIXING floats and ints, I'm talking about the fact that "1.0 + 2.0" is a syntax error in ocaml. You need "1.0 +. 2.0", because + will always and forever only handle ints. Well, unless the compiler makes some exceptions, but don't try this with your own operators, kids.Identity is polymorphic. Excuse me while I cheer. How about a function that computes something, because I do eventually have to degenerate to base types. Now there are polymorphic types as well, but you have to anticipate the types it may be and change it at the declaration of the type -- in other words, it's not inferable. Plus, the syntax of polymorphic types is an awesomely grungy wart, and can't begin to compare to type families.
I actually like ocaml, mind you. Unfortunately, it hasn't seen serious development around anything like smarter compiler feedback, let alone language features like type families. In fact, mentioning such a thing elicits so much negative advocacy, one gets the impression that the language definition has become Set In Stone For All Time Forever And Amen, and that only weird and crufty macro metaprogramming hacks in camlp4 will push the envelope any further.
I've finally had it: until slashdot gets article moderation, I am not coming back.
Actually, the phrase 'ad-hoc' here is the killer.
What is the type of this function?It can't be this:...because then this would make no sense:There is an experimental extension to Ocaml (called Gcaml) that gives support for explicit overloading to the language. But that keeps it from being 'ad-hoc' now, doesn't it?
It would be nice to get 'generics' added to Ocaml and there appear to be some sound reasons for doing it, if the comments from the Caml team at INRIA are to be believed. However, it doesn't seem like there is any sound way to do it and still be 'ad-hoc' about it.
You're going to have to explicitly indicate all the specializations of an overloaded function or operator.
--
jhw
> "Hey they're not warts, they're beauty marks". Funny how it becomes a
;; ;; ;;
;; ;; ;;
> Good Thing in one's Favorite Pet Language. I'm not talking about
> MIXING floats and ints, I'm talking about the fact that "1.0 + 2.0" is
> a syntax error in ocaml. You need "1.0 +. 2.0", because + will always
> and forever only handle ints. Well, unless the compiler makes some
> exceptions, but don't try this with your own operators, kids.
Ok, so you have to remember to type a period when you perform arithmetic
operations on floats. This is a minor annoyance at worst. It took me
all of maybe five minutes to get used to this when I started programming
OCaml. Syntax quibbles are about the most petty thing to focus on in
debating the merits of a language. OCaml gives me so much power that
I would gladly type an extra period after every keyword if that's what
it took in order to use it. Besides, the compiler will remind if you
forget, so it's not like you'd introduce a hidden bug in to your code
that will end up corrupting your data if you forget. So I really don't
see this as a big deal. Your milage may vary.
> Identity is polymorphic. Excuse me while I cheer. How about a function that computes
> something, because I do eventually have to degenerate to base types.
Well, you can build data structures using parametric polymorphism:
# let f x y = x::y
val f : 'a -> 'a list -> 'a list =
# f 1 [2; 3]
- : int list = [1; 2; 3]
# f "foo" ["bar"; "baz"]
- : string list = ["foo"; "bar"; "baz"]
similarly:
# let f x y z = x,y,z
val f : 'a -> 'b -> 'c -> 'a * 'b * 'c =
# f 1 2 3
- : int * int * int = (1, 2, 3)
# f "foo" "bar" "baz"
- : string * string * string = ("foo", "bar", "baz")
> Plus, the syntax of polymorphic types is an awesomely grungy wart, and can't begin
> to compare to type families.
What is ugly about the parametrically polymorphic functions above? They seem quite elegant to me.
I'm not the one having made the original comment but, using exceptions for break or return?
Bleach, this is ugly!
Break and return have a purpose (changing the flow of execution), exceptions a different one (reporting error), mixing both is ugly.
What the point of using a "clean language" if you need to hack around the language?
Me I tried to learn Ocaml and didn't manage to do it..
Now I'm learning Ruby which is much more easy for my poor brain, and it is also the most readable language I know (unfortunately it is slow also).
For example, if no two objects have the same value, and they are all integers in the range 0 to k, they can be sorted in O(n) by using an array of size k.
Those who sacrifice security to condemn liberty deserve to repeat history or something. - Benjamin Santayana