173 points · by qsantos · 3y ago · 152 comments
OCaml supports type annotations practically anywhere, if you want to add them. Alternatively, you can use an editor that supports querying or showing types for bindings. VSCode and Emacs support this.
> Remember recursion? How about linked lists?
A lot of beginner material uses List to introduce algebraic data types, inductive and equational reasoning - but you don't have to use them. In fact, the standard library encourages Seq instead over List.
It's a shame the author did not get past the basics, as there are many interesting comparisons to be made. For example, OCaml 5 effect handlers are a very interesting alternative to Rust's Async.
I have repeatedly found this the hardest part of learning OCaml - it seems really difficult to find a tutorial that explains how to write OCaml as a real developer would working with production OCaml. Like, I don't need another explanation of sum types or recursion, these are things I'm already using regularly. I'm more interested in the things that OCaml does uniquely that I won't have seen in other languages.
For example, which sequence type should I be using most often? And how often should I be using refs/mutability? And there's lots of alternate stdlibs - should I be dipping into those? What does unit testing typically look like for an OCaml project (and what about other forms of testing)?
It's also very difficult to search for these sorts of things, because I feel like a lot of the results I get are for students learning OCaml as an introduction to functional programming, so questions like "how do I reverse a list" are answered by showing a clever recursive function that reverses a list, as opposed to the List.rev function.
I am not the author, but I'm in a similar situation (right down the Rust background and trying out OCaml for AoC), and I'd love to get past the basics, but it's very difficult trying to find worthwhile resources to do that with.
> For example, which sequence type should I be using most often?
You should basically default to list. If you need assignment and indexing or a 2D structure, use array. If you're writing generic processing code, use sequences if you can. Use sequence if you need lazy sequences.
> And how often should I be using refs/mutability?
Only when you need. I most often use mutability when interacting with unmanaged code, translating some Python or other imperative code before transitioning it to be more functional, and inside classes to manage internal state. Otherwise, I don't.
> And there's lots of alternate stdlibs - should I be dipping into those?
I'm not familiar enough with the OCaml ecosystem, but F# doesn't have this problem. F# has its own core library and for everything else, you just reach out to .NET.
> What does unit testing typically look like for an OCaml project (and what about other forms of testing)?
I personally use FsUnit, specifically the XUnit flavor. https://fsprojects.github.io/FsUnit/xUnit.html. FsUnit is an F# DSL over NUnit and XUnit, so it fits in well with F# and functional thinking but also plugs into the IDEs and `dotnet test`.
I want to like the language very much, so that is helping. That CIS310something or other course that is on Youtube is pretty cool, although a little slow for me (this is usually my issue with tutorials) but I did find the book online and that is great. I definitely hear you on the search results thing...
I started declaring all my types manually just because that's what I'm used to but switched back just because I feel like matching the 'standard'. I will definitely admit to a dodgy AOC solution (hard-coding with magic values).. but overall I'm enjoying it quite a bit.
Uhu? Never heard about Seq before! Seems to have been introduced in 4.07 which was released 5 years ago, which is basically yesterday in terms of stdlib api. Set and Map, sure, but Seq? Lists are ubiquitous and they are indeed a central data structure in ocaml code. For anybody also wondering, Seq is a datatype for iterators (ie thunked lists).
This is actually one of my grief with OCaml. I wish I didn't have to use Core. I don't look much at the std library anymore.
My other grief is async (Lwt or Async). It forces to use monads which don't look very pretty in OCaml. That being said, I haven't looked at what OCaml 5.0 bring to the table on that front. This was my experience 5 years ago basically...
Using an editor that shows type inlays (e.g. VSCode) helps a lot but not fully because a lot of types are inferred as generics.
You're also correct that you don't have to use lists, but again most OCaml code does.
Most OCaml code use .mli which does have types. This is the recommended practice but I noticed a lot of beginners coming from other languages are reluctant to use them (because of duplication). It's a simple idea but I think it's a strong point of OCaml and it makes easier to program "in the large" than Haskell for instance.
And I did not experience any advantage of separate signature files so far, but I also haven't written anything large in OCaml (>100 kLOC).
If the list is not being used in a critical section, what's the problem? The implication here is that OCaml is slow or inefficient. OCaml is often orders of magnitude faster than other high-level languages (e.g. Python). Arrays in OCaml can result in some very fast code.
That is because they are generic most of the time.
This is also fun when using `#trace`in the REPL and all you see is `<poly>` instead of the "real" value
* intent of the author not clear
* auto-complete etc. doesn't work as well
* type errors not caught as early (for generics this means you get super confusing type errors)
Obviously some functions are intended to be generic (e.g. operations on containers) but typical OCaml code seems to contain functions that are actually only called with one type - and the author only intended for them to be called with one type - yet they get inferred as generic.
Also, if you don't like the OCaml syntax, check out ReasonML, which is an alternative OCaml syntax that Facebook developed several years ago. It has the Algol-style that many modern languages today use.
I don’t think this is that bad for rust though. For (a), it turns out that tail calls can make debugging harder, and they can be incompatible with certain type system changes you might want in an ML, and lots of OCaml (perhaps not a true ML?) in practice uses little explicit recursion and instead first-class functions with names like map and iter rather than recursion. So I don’t really think it’s very important. Rust also has these first-class iterator functions although a bit less of map for containers that can have many things (e.g. vectors). Rust iterations allow for writing code that is more functional when memory/performance are stronger constraints because the pipeline gets composed together instead of producing lots of intermediate objects. For (b) I guess the big difference is that the usual tool in functional programming for manipulating data is creating new copies of immutable data whereas in rust it is controlling ownership and then just updating it (a middle ground may be koka where you write code in the former style but the compiled code inspects recounts to potentially just mutate instead)
I think the thing that tickles most people about Rust is the thoroughness of the type inference and type checking, which one generally gets from any ML.
As a Haskell fanboy, this is how I feel about Ocaml and F#.
I guess I would even say it's like... most people just want the banana, but got a gorilla holding the banana and the rest of the jungle as well.
This part specially about closures: https://blog.janestreet.com/oxidizing-ocaml-ownership/
https://blog.janestreet.com/oxidizing-ocaml-parallelism/ And yes, their changes introduce quite some additional syntax.
Thus, Rust for me serves mostly as a C/C++ alternative. I don't plan to ever write anything in C again, and even if it's not my goto language otherwise, for that I'm thankful.
https://graydon2.dreamwidth.org/307291.html
It seems to me that Rust evolved into a better C++, but it did not start out that way.
But it went a completely different way, ripping out any runtime it had, making reference counting a lot more noisy, etc.
It would be interesting to build a "simpler Rust"
In any case OCaml has memory safety, sort of (it has data races but as described in the paper "data races bounded in time and space", data races in OCaml doesn't lead to unrestricted UB like in Rust, C, C++, and most other languages actually) (unless you opt into OCaml's unsafe constructs like Obj.magic, which is like Rust's unsafe without using unsafe {} block), because it has a GC
So when you talk about safety in the context of exceptions, you probably mean exception safety rather than memory safety. Exception safety basically means you code works even if an exception is raised. Which is really hard to assure since as you said, exceptions are everywhere
But Rust suffer from this same problem! In Rust this is called panic safety and mitigating it has taken a great deal of complexity, with things like lock poisoning, which adds overhead but limit the scope of panics in multithreaded programs, and the UnwindSafe trait, which is probably a good attempt but is ignored in most of the ecosystem. Many people think such measures are inadequate and insufficient and prefer to run programs with panic=abort, which means to just terminate the program when there is any panic. (many C++ projects disable exceptions in the same way for example)
Which is kind of unfortunate because now there are many Rust programs that are only correct if you run with panic=abort, and will break if you enable stack unwinding (which is the default)
For reference, this is the type that is returned from catch_unwind: https://doc.rust-lang.org/std/thread/type.Result.html
But I completely agree that Rust has exceptions. They are even used in the toolchain implementation for non-local control flow.
And you're working with multiple definitions of "safety" here, and Rust sorta conflates them all via borrow checker, but the one people are usually most concerned with is memory safety which is not a concern for a garbage collected language.
I do seem to recall that StandardML did not have exceptions though. And I always felt that SML was the better language.
OCaml adding OO classes and exceptions and other 90s trends that actually have ended up not aging well...
> I have been writing a compiled, concurrent, safe, systems programming language for the past four and a half years.
Safety was always part of it.
Exceptions look remarkably wrong headed to me in retrospect. Allowing the caller to change the error handling contract and flow control.
use something like `Maybe` for the result - clumsy.
return (for example) 0, which is what most theorem provers (like Coq or Lean and dependently typed languages like Idris) do, that need their functions to be total
or throw an exception.
(C's solution of declari g it undefined behavior is missing).
Now, with OCaml's effect systém, there also is no need to use exceptions for control flow - which you should have never done anyway.
I never felt this was a problem when I did Java though (despite their awkwardness - basically forcing coders to not use checked exceptions.)
Rust's control flow syntax for Results and Options are very similar to this but with an added benefit: you don't have to use the ?-operator.
panics is different, however. They are more akin to the way any Java program will happily OutOfMemoryError or NoClassDefFoundError given circumstances not (always) in your control.
Since I was spending most of my time w/ OCaml at that point I thought it could also be a way to practice it further. So for a particularly easy problem it would go something like this: A straight forward, easy to read, performant C++ solution took me 10 minutes; an ugly unidiomatic OCaml version took me 30 minutes; and a beautiful idiomatic OCaml version using recursion that still no non-OCaml programmer could ever read took me something like an hour...
It really dawned on me that after weeks of studying OCaml I barely knew how to write anything particularly useful in it from scratch. Dealing with user input/output still seemed cumbersome, given everything's immutability... from an intellectual perspective it feels interesting, and I had fun with it, but for now I decided I couldn't see myself becoming productive enough in it to justify further sinking time into it. There's so much to still learn for me (doing a network related project at the moment learning a ton about networking, sockets, etc), that trying to become an unproductive OCaml programmer probably shouldn't be high up my list of priorities... and that is not to say people aren't productive in it, that's to say that I don't see myself becoming productive in it any time soon, compared to being productive in C++ while being far away from being any expert in it.
Maybe I'm too stupid for it, am not suited for it, need a few years of further programming to appreciate some things about it... but for now, sadly, I feel like I've wasted significant time I should have better spent on studying other topics and actually working on projects. And addendum: Never comment on downvotes, I know, but how I immediately got one for this comment... surprising.
> given everything's immutability
OCaml has a lot of mutable datastructures. It's perfectly fine to use them. Even though with experience, you realize there's often a a better/safer way to do it.
Also, I'm surprised that in 2023, functional programming still sounds like a mystery to some people. Python/Rust/C++ all have closures, immutable datastructures, their versions of the usual functional combinators, some form of variant types / pattern-matching (maybe not python?). C++23 even has monads. CppCon is full of talks of people realizing that they can write simpler code using this things. I believe all this FP tools should be in the bag of any proficient programmer.
Most of the code I used to write was just gluing libraries together, even heavily Object Oriented stuff was too complicated and becomes a spider web of dependencies, so I always hunted for better libraries, rather than try to extend existing ones.
Now, I've been writing Clojure for about 3 or 4 years, and I still struggle with certain functional and immutable algorithms. But, now when I go back to Python I occasionally get bit very hard from the surprising mutability. So my brain is definitely adjusting to the safety.
I'm still not fluent with a lot of higher order functional concepts. Though I think I'm finally understanding Monads and Transducers.
It's hard to break 10+ years of imperative habit. What really helped me was diving down into the core of how parsers and code evaluation works. I didn't read SICP, but understanding the plumbing of these languages can help ease the transition, at least for me...
Regardless, it's a lot of dedicated work that a lot of people don't want to invest.
That is true. Although, I would make the argument that F# and OCaml are two of the best most general purpose languages available. They support the imperative, OOP, and functional paradigms effectively equally. About the only thing you wouldn't use them for is embedded real-time programming. Other than that, they're statically typed with great type inference and sane scoping and syntax (I find F# to be the "cleaner" language) and are performant.
This sentence baffled mé, why would immutability be a problém with user input or output?
But changing the way how you solve problems takes time.
On the plus side these are the learning curves most worth climbing, as it broadens your understanding. That might be reason enough itself, but it might also make you a better programmer in your usual wheelhouse. Haskell, Forth, and assembly, are worth taking a look at for this reason.
If you want to go further down the exotic language rabbit hole, there's Mercury [0] and Joy, [1] both of which I keep meaning to learn. (Hadn't realised until today that they're both from the University of Melbourne.)
[0] https://en.wikipedia.org/wiki/Mercury_(programming_language)
[1] https://en.wikipedia.org/wiki/Joy_(programming_language)
I feel what is critical is to practice it more often and also to do a jump into how we think as a developer because OCaml is a functional language from the ML family. The way we have to design and think is not exactly the same as all the other mainstream languages.
Replace C++ with English and OCaml with Japanese or Estonian and you'll get the idea.
OCaml is a vastly different language from what C++ is. Switching to OCaml from C++ is not at all like switching to Go or Java. If you switched to OCaml from SML or Haskell, you would write a completely different opinion.
Paradigm shift takes huge mental effort, that's something you have to deal with, unless you want to confine yourself into the comfy world of familiar languages.
Never once thought negatively of Rust for this.
What does that tell you the sports he tried to do? Not much. It's all about his previous experience and skills.
Writing code in a functional language like OCaml requires a mind switch. This can take quite a while. It took me years to really 'get it' after having programmed for 30 years in imperative languages. Now I prefer writing code in FP for a lot of things, but not for everything. E.g. for coding some algorithms you have a much easier time when you can use mutable arrays.
A nice advantage of OCaml is, IMO, that it is not so strict about pure FP. E.g. unlike in Haskell, arrays are mutable by default.
(//) :: (Ix a) => Array a b -> [(a,b)] -> Array a b
that gives you a new updated array. As long as you no longer refer to the old instance, this is as efficient as a mutable array.But Haskell also offers the mutable STArray and STUArray, for boxed and unboxed types [1]. These preserve their purity by being monadic.
[1] https://hackage.haskell.org/package/array-0.5.6.0/docs/Data-...
On paper this is true, in reality though it probably is not. Immutable Haskell arrays are implemented with pointers, mutable arrays are implemented as contiguous memory allocations, so they have great cache locality.
I think this varies a lot from person to person. Rust includes syntactic sugar for imperative code (like `if let` and `let else`), and personally I prefer to use that when it's not too much trouble. I find it's pretty rare that I reach for map/and_then/etc.
https://pthorpe92.github.io/intro/my-story/
Looks like he's got everything lined up for success when he one days is let out of prison. Great attitude and lots of experience.
at some point i got sick of trying to debug mysterious compile errors about types in ocaml and started declaring types for all of my function arguments; ocaml lets you do that. an example is http://canonical.org/~kragen/sw/dev3/mukanren.ml (an implementation of a tiny logic programming language, sort of like prolog with superpowers; cw inappropriate intimacy) where, for example, instead of writing
let rec disj g1 g2 t = mplus (g1 t) (g2 t)
i write let rec
disj (g1 : goal) (g2 : goal) (t : state) = mplus (g1 t) (g2 t)
which is more code, to be sure, but i think easier to understand because it's more explicit. and the compiler doesn't report your type errors in the wrong function anymore when you do thatif you aren't sure what the types should be (easy when parametric polymorphism gets involved) you can paste the code without type declarations into the repl and see what it says
in this case that looks like this
# let rec disj g1 g2 t = mplus (g1 t) (g2 t) ;;
val disj : ('a -> 'b stream) -> ('a -> 'b stream) -> 'a -> 'b stream = <fun>
and in fact my `goal` type is more specific, `state -> state stream`, thus favoring comprehensibility a bit over flexibility (i can always go back and generalize the type more later)this makes the code a bit more verbose but most functions are more than five words long so it's not actually that bad
maybe i should declare the return type too
let rec
disj (g1 : goal) (g2 : goal) (t : state) : state stream = mplus (g1 t) (g2 t)
but so far parameter declarations seem like about the right balancedeclaring parameter types in your own code doesn't help with code you didn't write, but you can use the repl to find out what types the compiler inferred for it
# List.map ;;
- : ('a -> 'b) -> 'a list -> 'b list = <fun>
presumably editors with lsp support have some magic keystroke to display this on demand in your editor or something, maybe an lsp user can tell us what it isIt's not just me that has these issues. We introduced a tool into my company that is written in OCaml and I ended up spending so much time helping people fight OPAM that I eventually implemented a build cache system so they didn't need to actually compile the OCaml code at all. Saved a bunch of hassle.
It seems like a pretty decent language, aside from the issues the author of this article mentioned which are 100% true. But OPAM means I would never pick it.
Similar issue to Python, which isn't really a bad language (I'd say it's mediocre-to-ok), but the packaging and tooling story is abysmal.
More languages need to learn from Go, Deno and to a slightly lesser extent Rust which have all prioritised having a packaging system that doesn't make you want to tear your eyes out.
I always thought of Opam as the best feature of OCaml (especially compared to Haskell with two no-working package managers - and no, Nix is a problém, not a solution either).
Which is more than you can say for Python and C++.
Also, any decent IDE will show the types any way.
The complaint about the types is just strange and shows a failure in getting Rust out of their head. Once you get used to F# and OCaml, then going back to a language that forces type annotations everywhere gets old and seems archaic because you spend all this time telling the compiler what it already knows (in a language like F# and OCaml). However, there are times in which type annotations are needed, especially in F# when dealing with objects. I generally type annotate when I feel the name of the argument doesn't capture the type.
Writing F# often feels very Pythonic or Scheme-y, but at the end of the day, everything is being statically typechecked, so it's the best of both worlds.
I second this a lot. It's very strange to me that the author is complaining about powerful type inference. In my limited experience with ReScript, I've found the type inference to drastically reduce boilerplate while providing the same type safety guarantees as TypeScript. Moreover, your editor or IDE can always tell you what the inferred type is. I am really not sure what I am missing. The author headlines the paragraph with "Where are the types? [sic]" but the types are there! They're inferred and visible in your IDE!
The provided code snippet doesn't really help illustrate the point either, IMO. It will look unfamiliar to those who've never used OCaml before, and to those who have done more than a fizzbuzz in OCaml, it will look okay.
This is sometimes fine for internal code, but for external interfaces you want a human to determine the interface contract you’re agreeing to, rather than the minimal set or the maximal set of types the function supports as currently-written.
But a program should be optimized not for reading by a compiler but for reading by a human. This is essential for maintainability.
The question is not how hard it is for a compiler to deduce types, but how hard it is for a human (and a human that hasn't necessary written this ode, and hasn't necessary read and remembered the whole codebase) to figure it out.
It is not a simple question in general. Too much "infrastructure" clutter can hide the logic and intent of the code too. So to get the right balance in a language or in the code is non-trivial.
I absolutely agree, more than you could imagine, but I think this is not a case where that's the issue. Type annotating everything will quickly make the code harder to read. There's a reason why people like Python. But the problem with Python is that you don't have a way to figure out the types. With F#, just hover over anything and get the type.
> This is essential for maintainability.
Even more to the point, over type annotating will make maintenance harder, not easier. This is because you are fixing the types statically. When you then go to update code in the future, you have thrown out the benefits of type inference and now have to go around manually updating all of these type annotations.
So you took the quote a bit out of context. If you're type annotating code, you're telling the compiler something it already knows, you're telling the human reader what it can already find out immediately for any value, you're increasing the surface area of needed updates, and making the code harder to read.
Maybe they should do batch compilations as well, why bother with interactive programming.
For example, since functions are first-class objects, they are often passed around as parameters to other "higher-order" functions. Explicitly declaring the types of all these functions is tedious at best, and confusing at worst.
Also, I'm confused. We're using type driven development and writing the type signatures as part of the documentation, we should be thinking in terms of types, why would they be difficult to write?
pipe2: Parser<'a,'u> -> Parser<'b,'u> -> ('a -> 'b -> 'c) -> Parser<'c,'u>
That's fine for documentation, but I'm glad it's not cluttering up the actual implementation, which starts like this: let pipe2 (p1: Parser<'a,'u>) (p2: Parser<'b,'u>) f =
...
You can see how the code does explicitly specify the types of `p1` and `p2`, but doesn't bother spelling out the type of `f` or the return type. Although we are thinking in types the whole time, this sort of flexibility in the implementation is important for real-world functional code.(For anyone wondering, this function takes two parsers and a function as input. It sends the output of each parser to the function, and the result is itself a parser. This is equivalent to a well-known abstract function called `liftA2` in a language that supports typeclasses, like Haskell.)
[0]: https://www.quanttec.com/fparsec/reference/primitives.html#m...
[1]: https://github.com/stephan-tolksdorf/fparsec/blob/master/FPa...
You should not use them most of the time in functional languages (like OCaml and Haskell and...) for this reasons either, it's just that (almost) all examples for beginners use them because they are "easier" than for example trees.
Oh, by the way, OCaml does not have significant whitespace (but e.g.F# and Haskell do).
You also use recursion all the time, and no, recursion is not generally straightforwardly optimised into iteration unless you're doing trivial tail recursion.
I thought I was being slick