Objective Caml

The programming tool of choice for discriminating hackers

OCaml (formerly also known as Objective Caml) is an implementation of the Caml dialect of the MlLanguage. See http://caml.inria.fr/ocaml or better http://www.ocaml.org for more information.

SimplifiedWrapperAndInterfaceGenerator (SWIG) can be used to make calls to CeeLanguage or CeePlusPlus code.

One of the interesting things of Objective Caml is that it provides 100% type safety (apart from the Marshal module; see below), GarbageCollection, LexicalClosures, TypeInference, etc., and is often said to be AsFastAsCee by its supporters.

There is more information on this claim at

See also ComputerLanguageBenchmarksGame

The regular IcfpProgrammingContest winning entries tend to confirm this too.

It also compiles to ocaml VM bytecode, for platforms where native code compilation is not available.

Objective Caml, and FunctionalProgrammingLanguages in general, have many problems. First is really obscure syntax and compilers that are unhelpful when you get it wrong. The second is: if the Functional concept is so powerful, how come we need objects or monads or somesuch non-Functional things in order to do anything useful? An academic solution that has failed to find its problem.

In the same manner, detractors of C++ used to say that objects were useless to "real-world" programming.

Maybe a good proof of the powerfulness of the functional concept is that a relatively feature-full object system can be implemented in a few hundred lines of Scheme (OlegKiselyov's purely functional object-oriented system at http://pobox.com/~oleg/ftp/Scheme/index.html#pure-oo), and that by monads (which are a way of writing functional code, so not a non-functional thing) you can implement BackTracking, CallWithCurrentContinuation, exceptions, etc. See MonadicProgramming, OnMonads.

I disagree as well. The syntax took some getting used to, but aside from some awkwardness due to the lack of overloading (e.g. the third character in a string is s.[2] but the third value in an array is s.{2}.), the syntax is pretty straightforward. OCaml code tends to look somewhat similar to Lua. As for the monads point, you're probably thinking of Haskell. -- ScottVokes

To the contrary...

Objective Caml's syntax is cleaner than C++ and more expressive. I am also aware that monads are not required at all and that Objective Caml is more of a hybrid language; it is not a pure functional language so the argument is not really appropriate.

The main hang-up is a lack of industry support. Maybe Microsoft.NET will help in this respect since it will allow functional languages to use the CLR (See EffSharp). Once developers see that they can reduce the risk of using the language (since it sits atop a commercially viable platform) we *might* see some more use.

-- EricNewhuis

You can use Perl and Python libraries directly in OCaml programs, so lack of "industry support" might not be such a problem after all. See http://www.merjis.com/developers/perl4caml/ (my project, so I declare an interest) and http://pycaml.sourceforge.net/.

-- RichardWMJones

Flamebait? ;-) In what way is the syntax "really obscure"? I found it easy to grasp the basics of the syntax with just a few minutes reading a tutorial. -- AndersBengtsson

Beyond reading the tutorial, did you ever try to actually write anything in OCaml?

Eh, well, no... :) But I would expect to need at least a couple of days to really get started with a language.

I have written code in O'Caml, and I completely disagree with the comment of the esteemed AnonymousDonor. There is at least one factually wrong assertion in his statement (the comment that monads are "non-functional"; it doesn't get much more FP than monads!). If you don't like FP, you won't like O'Caml, but I strongly disagree that FP (or O'Caml) is somehow "flawed". The O'Caml syntax is, IMNSHO, well-designed and readable and a beacon of light in a world populated with abominations such as C++ or Perl.

-- StephanHouben

I agree that the compiler error messages could be clearer, though. -- ScottVokes

Objects and ReferentialTransparency are not contradictory either. (FpVsOo) The syntax of Ocaml is quite ad-hoc, but very natural (it seems to have developed from experience). -- PanuKalliokoski

I think that the biggest problem with functional programming languages in general is that most programmers with non-academic jobs tend to not be well-versed in it. So it forces somebody who is completely used to some mix of procedural and object oriented programming to think very differently from what they are used to.

On the other hand, I think that you can get some very good expressive capabilities out of it that can make your life easier. I'm meaning to give FP a good, honest, try now that I'm in the real world, where I don't need to deal with passing a class, which is responsible for many of the waves of revulsion associated primarily with ML. ;)

-- KenWronkiewicz

I spent Christmas trying to learn OCaml from the preprint of the O'Reilly book (http://caml.inria.fr/oreilly-book/) and found the learning curve initially quite high (It's a very well written book, but the topic can be hard work). I've programmed with C++ and C for many years but was always frustrated with the lack of sophistication in those languages. I studied functional languages when I was an undergrad (MirandaLanguage, HaskellLanguage, SASAL) but never anything as sophisticated as OCaml. Having perservered though the initial learning curve though I'm now enjoying the fruits of my labour. I've converted two programs from C/C++ to OCaml: a library for computing with concept lattices, and text processing/sparce matrix program for computing probabilistic models from text collections. Here are my impressions

Now I'm setup with OCaml I just can't go back to C or C++. As it says somewhere in the O'Reilly book: some parts of the program are best expressed using an imperative style, others a functional style. When coding in OCaml use the style that best fits your algorithm and then give it a functional interface.

-- RichardCole?

OCaml is a MultiParadigmProgrammingLanguage, but every paradigm is juxtaposed with its HindleyMilner TypeSystem. It can be tremendously helpful once you understand it (See: http://enfranchisedmind.com/blog/2008/04/14/useful-things-about-static-typing/), but it takes some getting used to. It made quite a bit more sense after I read TheLittleMler?. -- ScottVokes

Here are some more highlights of Objective Caml and its standard distribution:

So how many people use it? Has there ever been a successful, large-team project using it? In short, does it show any LanguageLifeSigns?

Yes, MLDonkey (http://www.nongnu.org/mldonkey/), a massively popular client for PeerToPeer networks, written entirely in OCaml. - MoeAboulkheir?

If you really care about how many other people are using it, I work for an investment bank doing derivatives pricing, and we use it for dealing with complex structures (shipping/aircraft financing, multi-tiered securitizations, etc). We use Python for prototyping with C++, but sometimes you just need a more powerful language. We wouldn't write everything in it, but sometimes you need the extra expressive power. The alternative is to write our own language, a route that most investment banks have been down at one time or another. If you are asking "how many people use it", though, you may well not need to use it yourself. If you're saying "I need a really expressive language", then ObjectiveCaml might start looking more attractive...

The majority of applications are in the research and academic realm. They range from theorem provers, compilers, to biophysics.

See http://caml.inria.fr/pub/old_caml_site/users_programs-eng.html and http://caml.inria.fr/humps/caml.html#Applications

There seems to be a shortage of ObjectiveCaml books for those of us who don't speak French.

TheFunctionalApproachToProgramming? (ISBN 0521576814 ) isn't bad, although it covers the now-obsolete CamlLight? dialect (basically Objective Caml without OO) rather than the current language. I hear O'Reilly have something in the works.

The French O'Reilly book has been translated into English for the most part. See http://caml.inria.fr/oreilly-book/ I found this quite helpful, though the learning curve is initially quite steep. The authors hit you upfront with all the (potentially unfamiliar) functional programming concepts, then imperative programming, and then a comparison for when each (or mixing) is most useful. There are ProgrammingExercises? at the end of every chapter. -- ScottVokes

Lastly, Microsoft Research is working on a version based on Caml (basically an older version of Ocaml, without OO) adapted to the DotNet platform, named F#. There are a few F# books available, Foundations of F# (http://www.apress.com/book/bookDisplay.html?bID=10240) and Expert F# (http://www.apress.com/book/bookDisplay.html?bID=10306)

There exists now a port of Ocaml for the DotNet platform, namely OcamlIL. See http://www.pps.jussieu.fr/sepps/abstract/29_0404pp_Montelatici.html

Jon Harrop's OCaml For Scientists (http://www.ffconsultancy.com/products/ocaml_for_scientists/) is a good book. (Albeit a little expensive)

Joshua B. Smith's Practical Ocaml (http://www.apress.com/book/view/9781590596203) has consistently poor reviews, however, and I found it quite disappointing. It's nice to have another EnglishLanguage OCaml book available, but the writing is dreadfully choppy, the explanations are often inadequate (in some places essentially saying, "don't worry about what this means"), and I've read in several places (though not personally noticed) that there are errors in the example code. -- ScottVokes

As a happy Python user, I recently learned OCaml to know what real FP is.

Real FP? There is no such thing, all functional languages have to offer an escape route (FunctionalLoopHole) to give you side effects. OCaml is a hybrid language - I think "Objective" gave the clue away..

It took several hours to learn basic things. However, I think OO concepts in Ocaml are overkill and I have not found any usefulness in them (ok, I have not understood all subtleties, but from what I saw in the Reference and tutorial - OO is a fifth foot for the dog). Theoretically, I wanted OCaml to become alternative to C for me. I hope it will be one day: efficiency of OCaml is great considering FP fanciness. Ocaml's real-use rareness is an obstacle though - http://freshmeat.net has only 3 (!) projects made with OCaml. I had hard time finding real life OpenSource code to learn more OCaml.

Weird, http://pauillac.inria.fr/ seems to have at least HeVeA, HaCHa, Active-DVI, MMM, efuns, GwML, and Coq. See also http://caml.inria.fr/humps/

More OpenSource OCaml projects:

I use FFTW and I couldn't believe this, I have always been told that it was C. And it is, sorta. Apparently they have ObjectiveCaml code that generates C code. Neat. http://www.fftw.org/fftw2_doc/fftw_6.html I agree that Ocaml would be quite complete enough without the object system, but it seems they were trying to break new ground with it. The object system's type system is more sophisticated than any other programming language's that I've seen.

I've happily used the OCaml application GeneWeb? http://cristal.inria.fr/~ddr/GeneWeb/ for several years. It's a genealogical application with a web interface. It works as it should on Windows and in Linux at least. The author's own database http://geneweb.inria.fr/roglo has more than 485 000 persons registered, and it's had almost 21 million hits since June 1998 (in May 2003). (My database is somewhat smaller. :) -- MagnusLyckaa

I am also a GeneWeb? user. One of the things that really impresses people I show it to is the relationship calculator, which also has a tree-style output. It has always seemed to me that you would need a very powerful language to do that kind of thing! --PaulMorrison

Trying to understand OCaml but frustrated with the online documentation? Wondering what "->" means? Here's a useful site: http://www.cs.ait.ac.th/~kitt/caml/.

Got any more?

There's a great new tutorial at http://www.ocaml-tutorial.org/ by Richard Jones. There are also some useful links at http://donkin.org/bin/view/Main/OCamlLanguage. -- RichardDonkin

Yet another Ocaml GUI. After Tk, Labltk, LablGtk?, Osiris, there is Fox. Fox Toolkit is a GUI library developed by Lyle Johnson and released under the GNU Lesser General Public License. See http://www.fox-toolkit.org/ to get more infos. I'm developing a Swig Windows project with MSVC in order to give this new GUI available for Ocaml. My first experience with Fox is FXRuby (see http://fxruby.sourceforge.net/), and it works very fine. Anyone interested? Here is a link to some samples with Fox / Ruby (see FXRuby paragraph here: http://wiki.rubygarden.org/Ruby/page/show/LionelDurigneux) I have to left my project soon here : OcamlFox?, it's not done yet, but soon. -- LionelDurigneux

Fox Toolkit is developed by *Jeroen van der Zijp*. Lyle Johnson is the developer of FXPy and FXRuby.

Swig is the SimplifiedWrapperAndInterfaceGenerator, which supports calls from ObjectiveCaml to C or C++.

If you can read Chinese, I have two articles in Chinese about O'Caml which appeared in IBM DeveloperWorks Chinese site. -- ZhaoWay

If you're looking for a slightly more readable way to do simple string parsing than adding and subtracting lengths and then sprinkling "+ 1" and "- 1" until it works, here's a little GPLed O'Caml module that'll let you say things like "substring after start of first 'foo'."

If you'd prefer it released under the LGPL instead, drop me a note. -- DanielBrockman

One of the interesting things of Objective Caml is that it provides 100% type safety

Could someone please show an example of Objective Caml's type safety compared to some IllTyped? Java/C++/Eiffel?

Actually the above is wrong. Ocaml has one major hole in the type systems left there on purpose. Basically by design they optimized the hell out of it, making it very fast, but they removed all runtime type safety. In the OCAML runtime values are just buckets of bits (or at least as far as I can understand, if somebody knows better please correct me). This is generally covered by a very good and very powerful static type system. However, when you serialize and deserialize values to and from external channels, all the bets are off and SIGSEGV is unsurprising. Therefore as bad as it is Java's type safety is way safer than OCAML's.

If you're concerned about this, just don't use the Marshal module. It is possible to reimplement the functionality of Marshal in a typesafe (StronglyTypedWithoutLoopholes) way. Marshal is one of a few things that would have to be removed in order to use OCaml as an ObjectCapabilityLanguage; otherwise it is very close to being one.

That's just as appropriate as telling a schemer not to use the read function. The functionality provided by Marshal is just essential in many domains of programming, and has been traditionally provided from the days of Lisp all the way down to modern languages.

I'm curious what's your proposal to retype Marshal module as to make it type safe, and whether you can do it within the current (3.07) limits of the language. --Costin

I'm afraid I'd have to agree that marshalling is essential. I have reason to think that dh is correct that it could be done safely, but it might be quite a large reimplementation - just based on general considerations, not in regard to OCaml in particular. -- dm

He would just have to provide a feasible solution with regards to the typing issue. Implementation is irrelevant, the current existing implementation is absolutely safe in its internals, it is just that its typing is unsafe. It produces a perfectly legal value or a safe exception, it's just that the typing of that value is lost as a matter of language/runtime design. If the typing problem is solved the other issues are marginal, and I have reason to claim that it cannot be adequately solved without providing typed values in the runtime heap (which Ocaml currently doesn't) and therefore providing a runtime-checked type cast. -- Costin

See OcamlTypeSafetyProblem.

So the question should be: does ObjectiveCaml type system help me finding more SourcesOfBugs than Java's at compile time?

That certainly would be true of other pure functional languages with HindleyMilnerTypeInference like Haskell, without question, so I don't see why it wouldn't be true of OCaml, too. They're both dialects of ML.

They were both heavily influenced by ML, but Haskell isn't really a dialect of ML. Also OCaml isn't purely functional. Regardless, languages with HindleyMilnerTypeInference do in my experience help in finding a particular class of bugs at compile time (in fact, they completely rule out that class). These are not "deep" bugs that would take a long time to find or fix if found at run-time, or that would be unlikely to be found at run-time, however. It's nice to be able to make a change to a large system and be immediately notified what it breaks (without writing any unit tests). It may initially seem like an irritable compiler, but it can also be a great debugging / refactoring aid. The OCaml compiler is also *very* fast. -- ScottVokes

Speaking of "type inference"... I will never switch to O'Caml until its type-inferer gets smarter. Why? I would miss OperatorOverloading. Even if it is sometimes an impedement to understanding (especially with inconsistent overloads of operators [like x << y means x.append(y)]), why must I write

    let average a b = (a +. b) /. 2.0;;
instead of
    def average(a, b) = {(a + b) / 2}
(as you would say in another Functional/ObjectOriented language, NemerleLanguage)?

Sure, the former is more consise for this one, but what about a monster like (and excuse me if I get the syntax wrong)

    let quadratic a b c = 
        sqrt(square(b) (* Does OCaml have a ** operator? *)
        -. (4.0 *. a *. c)) -. b;; (* not returning a pair for sake of space *)
    def quadratic(a, b, c) = {sqrt(square(b) /* does NemerleLanguage have a ** operator? */
         - 4*a*c) - b} /* Not returning a pair for the sake of space
Now, imagine stuff like that multiplied over an entire program, and Nemerle wins easily. --AnonymousDonor (propose: AnonymousKidHidingRealNameFromPerverts? :)

See also EffSharp (F#). For differences between OCaml and F#, see http://research.microsoft.com/projects/ilx/fsharp-manual-extras.aspx

Two major problems I have with ocaml: lack of overloading (ala Haskell type families) and lack of machine types (try expressing an unsigned 32 bit int without having to use a module for it. Now go try writing a network stack in ocaml without machine words). Overzealous monomorphism restrictions also do very little to enhance reuse.

In response to various comments about the OO part of OCaml being overkill... well, yes, it is really, but it can be very useful in certain circumstances. I don't generally use it for general data structures and so on, but two times I have found it very useful are when writing an asteroids-ish game with a lot of different types of sprites and enemies and so on, and when writing a basic GUI system for said game. I could've done both without using objects and classes, but using the OO features made the code a lot easier to think about and understand, as well as write.

Note that games and GUI's are just about the only areas I consider OO a VERY good thing to have rather than an "I could do just as well without it" thing to have. ;-)

Do you see EffSharp as trying to kill off Ocaml and gain MicroSoft entry into academia? I know many universities are MS-hostile or vendor-neutral. I'd bet MicroSoft wants to convert all functional languages over to EffSharp as a stepping stone to merge (force) them into .NET in the future.

The pattern I find the object layer useful for is to wrap the clearly non-functional , side-effect-heavy sections of my code into opaque boxes that pass messages back and forth; this makes it easy to port over the well-tested object-oriented design patterns for application design while using easy-to-verify functional code for their internal logic. Put differently, I put most of my mutable values behind an object interface, both to emphasize that I'm dealing with mutables and because mutables most often occur in situations I'm more familiar with addressing in an oop setting. I build as much of the actual logic funtionally, and then use objects to handle the mutable bits -- files, networks, user interaction -- that provide the actual data to 'drive' the functional core.

In Haskell you'd wind up adopting a similar strategy -- wrapping mutables like I/O in monads -- but where Haskell fails as a practical language is in that it's often difficult to re-use non-monadic functional code in a monadic context as-is; without a mix of luck and foresight you'll wind up rewriting a lot of your early code sketchs in monadic form, because the monads have a way of infecting anything they touch upon. From a certain standpoint that approach is superior -- it ensures that everything interacting with the real world does so cleanly -- but as a practical consideration it's a huge headache, and entirely avoided in OCaml. I'd bet even money that whatever time-to-finished-product is lost by Ocaml's lack of Haskell-style typeclasses is gained back and then some by not having to rewrite big chunks of code into monadic style once they touch the I/O or similar layers.

I think the 'grand project' idea is a good one, but it's important also not to clone something already done well -- I'd suggest something where the speed is an asset but the expressivity of the language is the real drawing point: something useful with large scale symbolic and numeric analysis, for example, that would be useful to more than just scientists and academics. I'm thinking datamining of some sort, perhaps easily-interfaced website visitor pattern datamining and analysis or social network analyis sorts of things. Basically something that hits the sweet spot of being computationally sophisticated to implement, easy to understand conceptually, and of appeal to joe-avetage-geek.

ObjectiveCaml seems to me like a good complement to PythonLanguage. Both were explicitly designed to be practical languages for rapid development, and both support MultiParadigmProgramming (though FunctionalProgramming in Python is somewhat hindered by its weak lambdas, and GuidoVanRossum has no intention of changing this). Python's compile-time error checking is rather weak, whereas OCaml's is extraordinarily powerful (and, er, OCaml compiles). At the same time, Python has a significantly larger standard library and community (a ChickenAndEggProblem) than OCaml. -- ScottVokes

ThisPageScored: 0384

CategoryProgrammingLanguage CategoryFunctionalProgramming

EditText of this page (last edited October 9, 2013) or FindPage with title or text search