What I wish I knew when learning OCaml (2018)
baturin.org
baturin.org
I'm really hoping it breaks into the mainstream such that it gets the investment that other mainstream languages get (hopefully said investment will smooth out these rough edges).
First and foremost, F# is functional-first, while Rust isn't really functional. Rust takes some useful features from functional languages, to be sure, but the overall paradigm is more procedural. A lot of key functional idioms and design patterns don't really fly in Rust because it's difficult-to-impossible to make them play nice with its memory management model.
Rust has traits, but not OOP. F# has OOP but not traits or typeclasses.
F# is immutable by default, and discourages mutability. Rust is immutable by default, but embraces (and tames) mutability.
I don't know how practical it would be to implement in practice.
The only thing missing from F# is an Elixir/Erlang/OTP-like process system (`MailboxProcessor` is pretty good though), but then again, every language except Elixir/Erlang/OTP is missing that.
Love the language though I have spent only a week working with it. It seems to have a lot of things I liked in Kotlin.
https://fsharp.github.io/fsharp-core-docs/reference/fsharp-c...
https://fsharpforfunandprofit.com/posts/concurrency-actor-mo...
I haven't looked at Orleans in a while. Last time I did, I came away with the viewpoint that it was very much designed to have a C# interface, which while manageable in F#, doesn't really provide for an idiomatic F# experience. I'm also not too sure, but I think it basically requires a cloud or distributed environment. Can it just be run on a local computer?
But even the `MailboxProcessor` doesn't do what Elixir and Erlang do on top of the BEAM VM. An instance of a BEAM VM is a single OS process, but the BEAM can handle millions of Erlang processes, which are not OS processes or even threads. They are their own thing that are extremely lightweight. The BEAM scheduler is very nice as well, such that it switches among all the running processes.
Even though I develop in Elixir, I am not yet a BEAM expert. So before I say something incorrect, I recommend taking a look at the talk The Soul of Erlang and Elixir by Sasa Juric.
https://www.youtube.com/watch?v=JvBT4XBdoUE
It fully encapsulates and describes what makes processes so special in Elixir and Erlang.
There is the Gleam language, which is a statically typed language on the BEAM VM. However, they moved away from the ML-dialect syntax, which is unfortunate.
I have never tried it though
The other thing I didn't like (which was something shared with other statically-typed languages) was feeling like I had to wrestle forever with the compiler to get my program to run. It just always felt so much easier to write programs in dynamically typed languages. Sure, my programs might have bugs in them, but I could iron them out over time, and my programs change so much anyway that pieces of buggy-but-working code in those dynamically typed languages might be replaced wholesale anyway before I even ran in to the bugs.. so the pace of prototyping in dynamically typed languages is much faster, in my experience.
As for the error messages requiring expertise in type theory, it sounds as an exaggeration, esp. when not using advanced features.
I annotated the hell out of my programs, and completely avoided OCaml's type inference as much as I could because I saw that it could not guess what I meant. I still had tons of problems understanding the error messages.
Error messages like "This expression is of type X but an expression was expected of type X" were not uncommon, and super frustrating.
The type checker and the type inference parts of the compiler are one and the same. If the type checker can’t infer what you mean you are most likely writing invalid code.
> Error messages like "This expression is of type X but an expression was expected of type X" were not uncommon, and super frustrating.
Ocaml is a strongly typed static language. As such your code has to respect type constraints. It’s very much a feature not a bug.
Still to be less defensive I too sometimes wish the error messages were more clear in highlighting why a certain type was expected but at least Ocaml provides tooling to live check the inferred type of any sub-expression while you edit your code.
Of course I'm writing invalid code: that's why I'm getting error messages. The problem is that I'm having trouble understanding why it's invalid. Error messages are supposed to help me here, but quite often they didn't.. they just led to more confusion... especially in complex code, where I needed help and clarity most.
That's reasonable if the error message were "This expression is of type X but an expression was expected of type Y". But the worst error message in the OCaml interactive toplevel is when they're the same. This happened when you defined a new type named X (which, incidentally, must be lowercase), but there were still references to things of the old type X.
I think this has been fixed in recent versions of OCaml.
The problem is that it would happen often in the interpreter when you were interactively trying stuff out, because when you're trying stuff out, you change the definitions of things.
Python actually sort of has the same problem not only when you use an interactive interpreter but even when you reload a module: the new class definitions don't modify the old one, they just get bound to the same name. So it's easy to end up with two alglayout.Vbox classes or two diff.Formula classes in the same interactive interpreter at the same time. But it's much less of a problem in Python because Python usually doesn't care what class things are, just what methods they define, so objects belonging to both classes can coexist peacefully. The usual exception is when you have an isinstance check somewhere.
That particular error message has been gone from OCaml for years now.
With experience, I am more or less able to preemptively add the annotations that will probably help (e.g. aiming avoid accidentally polymorphic functions, the return type of mutually recursive functions, etc.).
I don't think I have ever gotten "This expression is of type X but an expression was expected of type X" outside of the toplevel with type re-definitions, and recent OCaml versions have a nice error message for this now:
Error: This expression has type t/1 but an expression was expected of type
t/2
Hint: The type t has been defined multiple times in this toplevel
session. Some toplevel values still refer to old versions of this
type. Did you try to redefine them?
In general the error messages have been continuously improving in recent years.I don't know much about type theory but I did eventually manage to learn to interpret OCaml's type errors well enough to get things to compile. It still feels like driving a car by scraping it along a highway guardrail but it's often better than testing. I have to write twice as much code as in Python, it takes me longer to get it to run, and I still can't call it from C or Lua, but it runs twenty times as fast as Python and the process of thinking through the types helps me a lot to write code that works.
I keep hoping I'll internalize the type system enough that my programs run the first time they way they do in Python, but it hasn't happened yet.
I still often write a prototype in Python, though.
Haskell has a few niceties when trying to debug type errors nowadays. For example typed holes that allows one to spice in `_` within code and the compiler will tell you what type it expects you to replace that hole with, alleviating many issues I had previously. But in the same sense I'm in agreement with you, and I've been more productive when writing Guile/Chicken Scheme code for small tools.
Interestingly I've binged on OCaml videos recently, because I would find it interesting to work with it some day. From a distance what I like about it (aside from the functional language goodness) is that it supports objects, has row polymorphism, optional arguments, and imperative constructs (I sure like my mutation heavy for/while loops when prototyping code).
OCaml's syntax is pretty annoying but type inference is actually amazing.. I changed my mind over it, as previously I thought explicit type annotations are simpler. Turns out, it would be humanly impossible to explicitly annotate every piece of OCaml, just let the compiler do it for you
I think it's too much to say that all Standard ML compilers work or one way or another. There are 6 major compilers and a number of minor ones.
They don't really follow the same approaches in general.
I do think I've partially ascended into senior dev galaxy brain around syntax though. For the most part I think they're all fine and also all bad and also don't matter very much at all.
What does it lack that prevented it from gaining wider acceptance? Surely buy-in from a large company was an issue, but even F# hasn't seen any significant uptake. Is it really the lack of curly brackets? That didn't stop Python...
Is it just that being labelled 'functional' was a huge stigma for a very long time?
I doubt that. There are plenty of American SML dialects and F# is about as American as it gets, but neither of these languages saw any commercial success.
I don't think being labeled "functional" was ever a huge stigma. Being labeled "Haskell" is a huge stigma in some circles, but OCaml's never been labeled "Haskell". Until about 10 years ago functional programming didn't become popular enough to have any kind of popular opinion, positive or negative, and the people who knew about it generally thought it would be nice to do more of it.
Mostly I think people use a programming language either because they already know it or it's the scripting language for an environment they have to use. Assembly was the scripting language for your CPU, especially in mainframe days. BASIC was the scripting language for personal computers. Visual Basic was the scripting language for WIMPs. VBA was the scripting language for Excel and Word (previously Excel had a table-based macro thing). sh was the scripting language for the Unix filesystem; C was the scripting language for the Unix system call interface, and a nice upgrade from assembly. JS was and is the scripting language for the browser. Lua is the scripting language for WoW, Roblox, and Minetest. Perl was the scripting language of the WWW, then PHP was, or Ruby if what you really want to script is Rails. SQL is the scripting language for your database. Objective-C was the scripting language for NeXTStep; now Swift is. MATLAB was the scripting language for EISPACK and later *PACK and BLAS, though it had some competition from IDL for a while. Now Python is the scripting language for Numpy (and thus BLAS), Matplotlib, and TensorFlow. Only a few popular languages are exceptions to this rule: Fortran, COBOL, C++, Java, R, Pascal, Golang, and C#.
OCaml? OCaml is the scripting language of ocamlyacc and Coq. If you write OCaml then it's probably because you like Coq. This may have been a public relations problem in the Anglosphere, especially before same-sex marriage.
It's true that that is no longer the attitude. But if we want to understand why one language is more popular than another, we usually need to look at things that happened in the past, not just things that are happening right now. Even C's meteoric rise took 15 years from the first C compilers until it was the undisputed queen of programming languages, partly as a result of missteps made by the communities of ALGOL-68, ALGOL-W, Lisp, PL/I, SNOBOL, TRAC, FORTRAN, BCPL, and, perhaps most interestingly, MULTICS, 20 years earlier.
(It's also possible that my memory that the OCaml team treated the native-code compiler as a second-class citizen is incorrect, either because I misremember what they were saying or because I misinterpreted it.)
Projects like KDE, the GIMP, GNOME, Lucene, Jython, LLVM, Asterisk, Audacity, CMake, and Danger that got started in C, C++, or Java in the 01997–02002 period are still based on those languages today. OCaml would have been a reasonable language for all of these, though a new interpreter for Python in OCaml would have lacked Jython's key feature, the ability to easily script other things written in Java.
(Danger? Well, Danger as such ended in 02011, but Andy Rubin founded Danger in 01999 and left to found Android in 02003, which ended up making a Java-based smartphone much like Danger's Java-based smartphone, but less locked down.)
The fact that Java focused heavily on performance starting in 01997, when Sun bought Animorphic, meant that a lot of things were able to be written in Java in the 02000s, things that were previously just unthinkable. Lucene predates HotSpot by a bit, but the whole Hadoop ecosystem that grew out of it only makes sense in a HotSpot world. Minecraft obviously pushes performance heavily. SPARK is written in Scala, but OCaml would have been a good fit too—if Hadoop had gone that direction.
Figuring out why OCaml didn't get popular in the past is not a super useful exercise. It's more useful to understand what is needed to popularize it today.
The reasons in that case are that .NET was not originally cross-platform, which was a major blunder for Microsoft, C#, and especially F#. The other is that people have some weird stigma against Microsoft, despite it not applying in many cases. Although they should have started off cross-platform, the transition from .NET Framework, to .NET Core, and now to .NET 5/6/7 has been really impressive. That along with GitHub and Visual Studio Code, it's pretty amazing how much progress Microsoft has made for developers.
I just wish it would bring more people to F#, as it's sort of a Goldilocks language since it hits so many sweet spots.
And I don't know that F#'s syntax is better than OCaml's. Arguably it's worse. (I haven't tried using it so I don't know how the error messages are.)
Code returning side effects rather than having side effects, for example, is great, and I find myself returning to the principle in a lot of the stuff I design as an architectural principle.
The article says "::" is a Data Constructor. I can make sense of type 'a = Left of 'a | Right of 'a where Right and Left are the Data constructors but I don't see the link with the part I don't understand.
type 'a list = Cons of 'a * 'a list | Tail
...but with a fancy syntax for Cons and Tail.`type 'a t = Cons of 'a * 'a t | Tail` is defining a type with a constructor `Cons` with two arguments and a constructor `Tail` with zero argument. You write values of type `'a t` as `Cons (a, b)` and `Tail`.
`type 'a u = (::) of 'a * 'a u | []` is defining a type with a constructor `(::)` with two arguments and a constructor `[]` with zero argument. You build values of type `'a u` as `(::) (a, b)` and `[]`.
The rest comes from the special syntax support in OCaml for the `(::)` and `[]` names. Namely, `a :: b` is parsed as `(::) (a, b)`, and `[a; b; ...; z]` is parsed as `a :: b :: ... :: z :: []`, and hence as `(::) (a, (::) (b, (::) (..., (::) (z, []))))`.
Two pieces of data (with the constructor ::) with 1 being the head of the list (type 'a) and one being the tail of the list (type 'a list, a recursive definition).
:: is an allowed identifier in oCaml. If that is not allowed, the typical names are Cons for :: and Nil for []
Do you know Cons' meaning ?
Also why does :: act as a separator... ? Is that something you ca do with any Data constructor, I mean can I write type 'a = 'a Cons of 'a | Nil of 'a ?
As :: doesn't start with a letter, it's infix by default. But basically a binary constructor. If you want to create the List [1,2,3] in the prefix notation you might be used to: ::(1,::(2,::(3,[])))
So this type definition means that `'a list` is a list of elements of type `'a`, and it's defined by being something of type `'a` consed onto either another list of type `'a` OR the empty list, represented by `[]`.
type 'a list = [] | (::) of 'a * 'a list
When you write a list like: [x; y; z]
This is syntactic sugar for: x::y::z::[]
Which is syntactic sugar for: (::) (x, (::) (y, (::) (z, [])))
One can imagine using more ordinary constructor names instead: type 'a list = Nil | Cons of 'a * 'a list
And then the above would be: Cons (x, Cons (y, Cons (z, Nil)))
In OCaml, data constructor names mar be either a capital letter followed by set or more capital/lower letters/underscores/apostrophes/digits, or one of the following: []
()
true
false
(::)
Type directed constructor disambiguating means you can do funky things like: type 'a nonempty = (::) of 'a * 'a list
And write such a value just like you would a normal list. type 'a = 'a :: list 'a
It is syntactic sugar that allows me to get the * product type for free, right ?> Don't try to understand the error message except if you have no other choice.