19 ms·
OCaml Programming: Correct and Efficient and Beautiful
- m_a_g 4y agoI learned some Haskell years ago but it didn't stick with me. Lately, I want to get back into functional programming to see whether I'm missing out on something. This book looks nice, and so does OCaml. Any suggestions on books, courses, or resources on this subject? Also, just to get proper motivation, why should I learn functional programming as a capable Software Engineer?
- kubb 4y agoYou can strengthen the skill of thinking about your programs in terms of higher level abstractions, which allows you to have an overview and reason about larger systems.
- yakak 4y agoDan Grossman's Programming Languages is a great 3 language online course. It gives you the opportunity to compare standard ML, ruby and racket. Before that course I was already grouping languages by inheritances from C or Lisp families, but really started to recognize and appreciate ML more.
- bhrgunatha 4y agoBerkeley's Programming Languages and Compilers references this book and you get to apply OCaml to something non-trivial. https://inst.eecs.berkeley.edu/~cs164/fa21/ https://inst.eecs.berkeley.edu/~cs164/fa21/
- tgflynn 4y agoIt doesn't appear from your link that the course materials are available online though.
- bhrgunatha 4y agoOn the schedule page, there are links to further material. I don't think you can do the drills or exams, but you _can_ do the homework if you have a github account.
- tremon 4y agoYou should learn multiple paradigms to broaden your horizon, so you are able to approach a problem from multiple angles and decide on the best design approach. I don't write in a functional language in my day job, but I'm much more aware of global state and side-effects in my code than before. We mainly write in Python and C#, but I encourage my team members to dabble in SQL (for dataset manipulation) and Haskell (for functional purity). If anything, it makes them understand LINQ better.
- ufo 4y agoFor Ocaml in particular, one thing that is pretty cool about it is the module system. Although we unfortunately can't use this module system in other languages, it taught me some interesting lessons about abatract data types.
- ufo 4y agoAnother thing I recommend everyone to learn at least once is sum types aka algebraic data types. And how they are the dual to class based dispatch (what some call the "expression problem"). Sum types aren't exclusively found in functional languages, but they are certainly prominent in them.
- mejutoco 4y agoIMHO the main reason to learn functional programming is to learn to untangle state and behaviour.
- yawaramin 4y agoThe OP is a great book to learn OCaml. There is also a corresponding set of lecture videos on YouTube.
- kubb 4y agoMy introduction to programming course in my university was in OCaml. It was all downhill from there when it comes to the programming languages I had to use.
- newsoul 4y agoWhich university? Does the course have a public webpage?
- pwiecz 4y agoNot the original commenter, but my first year course of Introduction of Programming 15 years age was also using OCaml. There were two groups of students, standard one was using Pascal, and the functional one using OCaml. I was studying on Warsaw University and the lecture notes are in Polish: https://mimuw.edu.pl/~kubica/wpf/wpf.pdf https://mimuw.edu.pl/~kubica/wpf/wpf.pdf
- newsoul 4y agoThanks! 15 years, that's quite a long time ago.
- pwiecz 4y agoYup. I really loved all the functional stuff I've learned there from OCaml to SML+Extended ML, to Haskell. Unfortunately, I haven't had a chance to professionally program functionally since the n. :( It was all Java and C++. Though I like C++, maybe it's a Stockholm syndrome. ;)
- kubb 4y agoThat was exactly the course that I took at the WU :) Fond memories.
- lmm 4y agoCambridge does this (or did when I was there); https://www.cl.cam.ac.uk/~lp15/MLbook/ https://www.cl.cam.ac.uk/~lp15/MLbook/ is the book for the course (available online).
- sshine 4y agoI spent a lot of time on Standard ML in university. OCaml was always portrayed as the engineer's alternative for real applications. I spent some time brushing up on OCaml a few years ago using Exercism.io. While OCaml is a personal "top tier" language, I'd always prefer Haskell, Rust or Scala. Type classes / traits just seem to beat a higher-order module system for me.
- xyproto 4y agoI also find it hard to spot why OCaml is the natural "step up" for creating real world applications instead of Haskell, Rust, Clojure or even Kotlin, C++, Python and Go.
- toolslive 4y agolet's see: - OCaml vs Haskell: eager vs lazy (=> memory consumption is more predictable) - OCaml vs Rust: OCaml has a GC (=> comfort) OCaml has tco (could not resist this ;) ) - OCaml vs Clojure: vastly superior typing system. (=> less bugs) - OCaml vs Kotlin: no JVM needed. - OCaml vs C++: more safety. once it compiles it will not segv. - OCaml vs Go: vastly superior typing system. (=> less bugs) - OCaml vs Python: vastly superior type system, way better performance. The biggest risk of doing OCaml (or Haskell or Rust) for extended periods of time is that you will be unable to hide your feeling of superiority towards (fe) a python developer.
- frizlab 4y agoWhat about Swift?
- KurtMueller 4y agoFor now, a good language if you want to develop apps for the mac ecosystem.
- Zababa 4y agoOn the server, less ecosystem than OCaml. Long compile times. A big part of its "market share" is taken by Rust instead.
- christophilus 4y agoI love OCaml. Fast builds, native binaries, fairly expressive and elegant once you’re accustomed to it. Now that it is multi-core, I hope it gains traction.
- mark_l_watson 4y agoThat is a great format for an online book! The text looks like it could be read on its own for a quick review, and the hundreds of short embedded videos dig into detail.
- lairv 4y agoEvery time I use recent "functional" languages (Rust, modern Typescript) I realise how great OCaml is
- munchler 4y agoHave you tried F#?
- lairv 4y agoNope, I must say I have only used a small subset of languages from the FP-language-zoo, so my opinion on OCaml might be biased But as an example when writing Typescript, I feel so frustrated of not having a clean way of doing pattern-matching
- pjmlp 4y agoYou will have to wait for JavaScript to add it first. The whole point of Typescript and why it is so successful, is because they only add type system on top of JavaScript. Pattern matching would introduce new language constructs beyond what is required for defining types.
- sn9 4y agoTypescript gets compiled to Javascript anyway. What's stopping any pattern matching construct from being compiled to vanilla JS? We already get stuff like type narrowing and generics.
- pjmlp 4y agoThe philosophy of not adding language constructs beyond what is required for the type system. Typescript code without type annotations should be JavaScript compatible, minus features still in flight for standardisation. There are other languages for that like ReasonML.
- zem 4y ago
- water8 4y ago
- cmrdporcupine 4y agoI'm so glad you took time out of your day to come here and tell us this.
- tgflynn 4y ago> It has no performance or coding benefit for teams larger than a few. That must be why Jane Street uses it then.
- darthrupert 4y agoAnd pretty much only them. Perhaps some day we'll learn how little the programming language matters for anything beyond coding.
- gjadi 4y agoWhen you look for job in OCaml, you can find several fintech and blockchain related companies.
- yawaramin 4y agoEver used AWS EC2? Docker Desktop? OCaml code is driving some of the lower-level performance-sensitive parts. That's a gajillion instances running globally.
- darthrupert 4y agoGood to know, thanks.
- muglug 4y agoI found my experience trying to work with a large OCaml base a nightmare — when signatures changed in an unstable dependency (e.g. function argument removed and nested inside another), the errors spat out by the typechecker were utterly incomphrehensible. This was largely due to automatic currying in OCaml — if I have a function call "some_function arg1 arg2" and "some_function" adds a third argument, that call becomes a function that requires a single argument, arg3, but the typechecker message that tells you all of this is well-nigh unintelligible. Switching to Rust was a blessed relief, not least because Rust has much better developer tooling and documentation (but also no automatic currying). It made me think that OCaml is efficient and beautiful if you're the only person touching your specific codebase (which I think is true in the vast majority of cases) or if many of your colleagues are deep OCaml officionados with PhDs, but it's not a good collaborative language for the rest of us.
- octachron 4y agoDo you have a more precise example in mind? The example that you are describing should emit an error message of the form This expression has type type_of_arg_3 -> return_type but an expression of type return_type was expected which seem alright to me. (But I cannot not be called an OCaml aficionado). The type error might be delayed in sufficiently polymorphism context but that is a more infrequent occurrence (outside of functors whose error messages have been improved in OCaml 4.13 partially for this reason).
- muglug 4y agoyup, specific error message is here: https://news.ycombinator.com/item?id=31861450 https://news.ycombinator.com/item?id=31861450
- abathologist 4y agoLooks like that is exactly the error message predicted. It’s expecting a list of result values, but is getting a list of functions from some stuff to that result. IME, it’s definitely true that OCaml doesn’t have the didactic error messages that many have come to like in Rust et al. They said, imo they generally give the information needed solve problems and I like their concision. It takes a bit of time to learn to read them however.
- jcelerier 4y agoI did a lot of my PhD work in OCaml. I hated pretty much every minute of it compared to C++, when comparing the exact same algorithms aha.
- immigrantheart 4y agoOh wow, interesting. Could you elaborate why?
- blackerby 4y agoA quick scroll through the comments and it looks like no one is actually talking about the book itself, so I will. I came across it at a really good time in my computer science self education. It helped me learn about some essential data structures and algorithmic analysis. The video lectures interspersed in the text augment the text and vice versa. The sections without videos were tougher for me to digest, but are written clearly and bear revisiting and study. If you, like me, are looking for a good next step after Grossman’s PL MOOC, I recommend spending some time with this incredible free resource.
- haskellandchill 4y agoI'm enjoying the discussion of commutative diagrams, abstraction functions, and representation invariants in section 6.3. It is very well motivated and easy to understand.
- zaptrem 4y agoI took this class last semester. Michael Clarkson is an awesome professor. After learning OCaml I want pattern matching in JavaScript! Beyond the language itself, it absolutely made me a better programmer.
- toastal 4y agoPattern matching without ADTs though loses a lot of the power. The fact that you'd still have to handle null/undefined cases means it's still annoying to use and hardly exhaustive.
- 0x69420 4y agoerlang/elixir programmers would disagree -- we match on ad-hoc dynamically typed tuples that serve broadly the same purpose as ADTs all the time, where the only exhaustiveness you get is the degenerate case ie `_ -> shit_the_bed()` especially common are pattern-matching assignments (technically `=` is the “match operator”) that idiomatically behave much like matches on the left hand side of `<-` in haskell do notation, i.e. inline runtime assertions on structure these communicate programmer intent really well! you could probably have them in static land in a non-`monadFail` context too, but you'd want dependent types or something lest you go the way of typescript and resign yourself to unsoundness in fact it's so nice that i feel pain in any dynamic language without full-fat pattern matching, like when i have to write disgusting if-else chains in complex nix expressions
- franz_kafkaagh 4y agoI write Elixir for work and I love most things about the language. The pattern-matching would still be made better with static checks. It sucks to have a function blow up at runtime because of something as trivial as args being swapped or some code somewhere changing its return types. Someone brought up Gleam earlier, but god why with that syntax? I'd still rather have dynamic checked pattern matching over the alternative.
- 0x69420 4y ago
- tgflynn 4y agoThis is a very specific question but I thought I'd ask it here on the chance someone might have a good answer. I've been slowly working my way through this course and I ran into an issue recently when I upgraded my OCaml installation to the latest version (4.13.1). With this version I find that the simple instructions for building an executable with dune (especially one that uses OUnit) given here https://cs3110.github.io/textbook/chapters/data/ounit.html https://cs3110.github.io/textbook/chapters/data/ounit.html no longer work. It seems dune now requires you to initialize a project. Does anyone know how to translate the instructions in the course to the current version of dune ? I realize I could install an opam switch for the previous version but I'd rather be working with the latest one. Just hoping someone might be able to save me an hour or so figuring this out on my own.
- shikoba 4y agoThe latest version is 4.14.0. Personally I write my Makefile myself and use them to build my projects. It works perfectly.
- octachron 4y agoYou can add a dune-project file at the root of your project with just `(lang dune 3.2)` (or your dune version rather than 3.2). The file can also be generated by "dune init project project_name" for fresh projects.
- tgflynn 4y agoThanks. It looks like all I needed was the project file. I was confused because when I followed the instructions to run dune init it created an entire directory structure and then I was confused about where my code should go (I haven't gotten to the chapter on modules yet).
- mc10 4y agoFYI: If you have more questions, the OCaml forum is very friendly and helpful: https://discuss.ocaml.org/ https://discuss.ocaml.org/
- frankohn 4y agoAs a former OCaml hobbyist programmer my take on these kind of books or articles is that, yes OCaml is extremely elegant and beautiful as a programming language and it shines for simple applications. Some parts of it are actually not so elegant, for example the object oriented aspect completely spoil the elegance of the core language. On the other side OCaml, as a pure functional programming language with immutable value by default doesn't scale well to large, complex application. Just the paradigm is no longer tenable and you need to switch at least partially to imperative programming with mutable variable. For example this is what it does the implementation of the OCaml itself. To develop further the point about "what doesn't scale" there is also the function with unnamed arguments and currying. While extremely elegant for simple programs it gets confusing for real-world applications when function needs quite a lot of arguments and there is no longer any obvious order to give them. If you stick with that and you choose an order it becomes arbitrary, difficult to remember and currying no longer makes a lot of sense. Functional programming with immutable values is a wrong pattern for programming languages. Many algorithms, almost all actually, are naturally expressed in imperative style with mutable arrays or variables. What is needed is to bridge the good things from OCaml, the type system, the pattern matching with tagged types into a modern, imperative programming languages. Rust is a sort of answer but they got it wrong because it is too low level about managing the memory, the ownership pardon, and everything else so programmers cannot just express the algorithm or the logic they want to implement but they have to spend a lot of mental energy thinking about ownership issues and unneeded accidental complexity like lifetime annotations.
- octachron 4y agoConcerning the issue with function arguments, this is one of the reason why OCaml has labelled arguments. And for instance, Janestreet's idiom udes labelled arguments as often as possible. Similarly, I am not sure what is the issue with using imperative OCaml for imperative algorithms when they are a better fit for the problem at hand?
- frankohn 4y ago> And for instance, Janestreet's idiom udes labelled arguments as often as possible. So you have to give up to one of pillars of the functional programming paradigm and you get a less elegant but more practical programming language. Otherwise I agree that using labeled arguments is mostly fine and doesn't completely spoil the language. The more serious compromise to the functional programming paradigm is the fact that you need to use mutable variables and imperative style programming. Once you do this you lose most of the elegance and attractiveness of functional programming. > Similarly, I am not sure what is the issue with using imperative OCaml for imperative algorithms when they are a better fit for the problem at hand? What I mean is that for any moderately complex application you need to switch to imperative style so the appeal of OCaml is mostly lost. You better choose a programming language that is designed for imperative programming since the beginning. The arguments I am giving explains why there are practically no real world applications done in OCaml. Some people insist using OCaml because they love the elegance of the language and I understand them but reality is it doesn't scale to complex applications. For people in Janestreet I think this is a sort of niche where they get an added value from OCaml thanks to its superior typing system and compile-time detection of many errors. I guess they care really a lot about the business logic of their applications and OCaml shines to ensure it is correct so for them the advantages out-weights the inconveniences.
- usrn 4y agoI really want to like ML but I have some complaints about OCaml in particular: The stdlib is very weak so everyone uses this third party library. That really rubs me the wrong way. All structures share a namespace for their elements which is super wacky.
- yawaramin 4y ago> The stdlib is very weak so everyone uses this third party library. That really rubs me the wrong way So don't use the third-party library then? There's a lot of functionality in the default Stdlib, use what you can from there and find third-party libraries for the rest... > All structures share a namespace for their elements which is super wacky. Not sure exactly what you mean here, perhaps that all modules in a single compilation unit are globally namespaced. Simple enough to solve nowadays especially with everyone adopting a common dune-led convention of namespacing by the library name.
- hahnbee 4y agoCornell alum here who took CS 3110. This course made me a better programmer, made me gain a sense of respect for OCaml and functional languages in general, and made me fall in love with CS. The textbook and professor are both phenomenal.
- 0x69420 4y agovery grateful that this course is free for all, and the youtube lectures are neat too real world ocaml 2e is nice, but like a lot of oreilly books about $LANGUAGE lately it's a lot of thinly-veiled $COMPANY opinions on $LANGUAGE best practices, where $COMPANY is, in this case, jane street. this is great if your motivation for learning ocaml is applying for a job at jane street if you think ocaml seems cool because wow jane street does epic hft in ocaml, then read real world ocaml 2e if you think ocaml seems cool because wow they wrote coq/fstar/the early rust compiler in ocaml, then read cs3110
- laylomo2 4y agoI actually find these thinly veiled company best practices fascinating. I find I can learn a lot of life lessons by reading a condensed account of a person’s entire life in their (auto)biography. For the same reason, I would hope to learn a lot of great real life patterns from a book called Real World OCaml… a kind of condensed (auto)biography of an institution’s experience with a technology.
- 0x69420 4y agosure, but if it's the reader's first introduction to the language (which rwo is positioned as), the reader is in a uniquely bad position to discern justified best practices from arbitrary ones, and truths about the language from opinions about it learning the language first, then someone's ideas about how it should be written (in this case, as encoded in a replacement standard library with a special module dedicated to making any call to the actual standard library throw a compile error), gives you the requisite context to understand the latter
- raverbashing 4y ago"beautiful" But then it has quirks like using ;; to end statements (EDIT: only in the REPL). And comments with that weird syntax But worse of all are the optional parenthesis in function calls. Yes, I know Ruby has it. But it feel super weird and a needless flexibility (that causes more confusion than it solves). I can't get over this stuff, sorry.
- jon_smark 4y agoI have to interject here for the sake of those unfamiliar with OCaml and who may take the parent comment at face value. Saying "it has quirks like using ;; to end statements" is misleading to the point of just being bogus. The double semi-colon is only ever used in the REPL. In fact, I've been programming OCaml for fun and professionally for over 15 years, and I've never used a double semi-colon in my code, nor have I ever encountered one in the "wild".
- raverbashing 4y agoThanks for clarifying
- toolslive 4y ago> worst of all are the optional parenthesis in function calls ?? > let r = some_function x y z in ... There are no parentheses here, and it's not optional. What you probably are missing is that if `some_function` takes 3 arguments, then `some_function x y` is a function value that takes 1 parameter (currying). Btw, iirc, SML doesn't have this: there you only have 1 parameter but it could be a tuple
- raverbashing 4y ago> Note how OCaml is flexible about whether you write the parentheses or not, and whether you write whitespace or not. from here https://cs3110.github.io/textbook/chapters/basics/toplevel.html#functions https://cs3110.github.io/textbook/chapters/basics/toplevel.h...
- belmont_sup 4y agoAnother day, another surprisingly large discussion around OCaml whenever it comes up on hn.
- pjfin123 4y agoI took this class!
- omginternets 4y agoForgive this tangential question, but does anyone know of a practically-oriented tutorial for implementing an ML-style language? Any format is fine, as are books.
- haskellandchill 4y agoThere's "Modern Compiler Implementation in ML" which has a section on making the example language Tiger a pure functional language. I don't have "Compiling with Continuations" but that might be even more appropriate.
- omginternets 4y agoBrilliant! Much appreciated, thank you. Also, I love your handle :P P.S.: are you referring to the paper entitled “the essence of compiling with continuations”, or something else?
- haskellandchill 4y agoThe book Compiling with continuations by Andrew Appel. Description says “Continuations can be used to compile most programming languages. The method is illustrated in a compiler for the programming language Standard ML.”
- he0001 4y agoHow do I know that some code is beautiful? And how will one know that it will always stay beautiful? Correct and efficient is one thing. Beautiful? This is off topic but topics like this grinds my gears as it’s purely subjective.
- vijaybritto 4y agoThis book's setup instructions are super easy to follow than OCaml's own site!!