r/functionalprogramming • • Dec 05 '21

Question Should I learn about monads?

I set out to learn about functional programming a few months ago. I come from a background as a web developer.

I read 'Professor Frisby's Mostly Adequate Guide to Functional Programming' (https://mostly-adequate.gitbook.io/mostly-adequate-guide/). It makes heavy use of monads, for example:

Either.of('The past, present and future walk into a bar...').map(concat('it was tense.'));

Maybe.of({ name: 'Boris' }).map(prop('age')).map(add(10));

This seemed interesting to me, but pretty mind bending and far from how teams I've worked with program.

In parallel I read 'Programming Clojure' (https://www.amazon.com/Programming-Clojure-Stuart-Halloway/dp/1934356867) and watched a some videos by people in the Clojure community.

The book raised several interesting thoughts in my head like 'How would I do lazy evaluation of infinite series in JavaScript?' and 'Transactions is an interesting model for async code that I hadn't considered could exist'. But the book didn't contain any discussion about monads as far as I can remember and the programming overall felt pretty familiar to me. I saw a video where (as I remember it) a prominent figure in the Clojure community criticised the Either.of construct in particular and similar constructs in general.

Originally I thought that I would build a web app using concepts like monads from the mostly adequate guide to gain new useful programming tools. But the Clojure track discouraged me. From that track I got the impression that I've gotten most of the value I can from the functional programming world by reading a few texts like 'Out of the tar pit'.

What do you guys think? Is reading 'Out of the tar pit' and being mindful of state and complexity enough or would I become a more productive programmer by getting practical experience from monads and similar to me esoteric stuff?

25 Upvotes

21 comments sorted by

10

u/beezeee Dec 05 '21

Is (...) enough?

What is your goal? "Enough" applies when you are looking for a means to an end. If you find it interesting and you want to learn about it, then the goal is to learn about it and it's "enough" when you aren't interested anymore.

That said, yes you should learn about monads. People who discourage you from doing so do not understand them.

4

u/mklasklasd Dec 05 '21

Thanks for your reply! Maybe my goal wasn’t clearly stated. Unfamiliar FP concepts like monads interest me. But other things also interest me. So I only want to go deeper than I am now if I think I will get tools that make me a more productive programmer.

7

u/beezeee Dec 05 '21

In my experience, learning to program with monads (and more broadly the category-theory rooted FP discipline that surrounds it) is one of the best things you can do for your productivity.

Done well, you'll root your perspective on programming in a much more solid mathematical foundation compared to the majority of code-centric buzz our industry tends to congregate around.

15

u/smudgecat123 Dec 05 '21

Monads are genuinely a super simple and useful abstraction so they are definitely something I'd encourage you to learn.

I learned them the hard way by reading every tutorial and blog post under the sun and then learning some category theory and came out the other side with some pretty strong opinions on the right way and the wrong way to teach them to other programmers.

Unfortunately, I think almost all tutorials teach them the wrong way.

Honestly, I think the best way by far to learn them is by working through the concept with someone else who knows what they're talking about (and there's a surprising number of tutorials written by people who don't).

So I'd be happy to run you through them over voice chat, at some point, if you like.

The only prerequisite to understanding would be understanding functors. Although I could run you through those without too much trouble as well.

6

u/Gigi14 Dec 06 '21

Any existing blog posts / tutorials / videos that you'd personally recommend?

3

u/smudgecat123 Dec 06 '21 edited Dec 06 '21

Some are definitely better than others. Stephen Diehl does a good job of explaining what Monads aren't (which genuinely is useful for avoiding unhelpful exposition on them). But his explanation of Monads in general is specific to how they're used within the Haskell ecosystem.

Every explanation I've ever read leans too heavily on some combination of category theoretic definitions (which are incomprehensible to programmers), how it's done in Haskell (which includes irrelevant aspects such as "bind", "do notation" or the "IO Monad"), or terribly imprecise handwavey analogies which usually miss the point of Monads entirely.

In reality, Monads are a well-defined mathematical construction given by a bunch of equational laws. It technically isn't possible to understand what a Monad is without understanding these laws in some form. Fortunately, in the context that functional programmers want to understand them (as data structures which can implement a particular API), these equational laws become simple, intuitive, requirements for the implementation of this API. (Requirements that can't be enforced by your language's type system alone).

Since I'm basically saying that I've never seen what I would consider a good explanation of Monads for an FP audience (in spite of how many there are), I might be tempted to write my own, but I don't know if I should contribute to this problem of oversaturation of Monad tutorials on the internet.

Feel free to DM me if you (or anyone else) has more questions. I can even tell you what details your favorite Monad tutorial is missing.

7

u/npepin Dec 05 '21

The question is "are monads useful"?

I'm not someone who does pure functional programming, it sounds like you may not be either, but I find monads really useful, especially in cases where you aren't sure what will be returned, like with validation or HTTP requests. They are also pretty simple, it's not hard to write your own.

For instance, if I am parsing a CSV file that some department made and not all the records are valid, I can put each line through a parser and convert it to a Maybe of X, and then I have an easy account of what records are invalid.

To take that a step further, you can instead return an Either of X or a list of Errors. You can display to the user what passed and what didn't and why.

A lot of languages have the Maybe monad built in, like nullable types. There is a good chance you are using them without even realizing it.

I know there is some higher level debate going on about if monads are useful or if they are overrated, which I think happened because there are thousands of tutorials that try and fail to teach monads, and so they get really hyped up as something interesting and crazy, but in reality they are simple.

Here is a good article on railway oriented programming that I think explains how useful the Maybe type can be.

https://fsharpforfunandprofit.com/rop/

10

u/fridofrido Dec 06 '21

Monads are most probably not really necessary to understand as a web developer.

On the other hand, they are not really that complicated. Monads are an interface (or API) for doing things in sequential order, more precisely, doing "actions" and binding the results of said actions to variables.

Consider a hypothetical program in a hypothetical language:

function(a,b) {
  x = action1(a+1)
  y = action2(b,2*x)
  z = action3(a,y+5)
  return (x,y,z)
}

If this looks like normal imperative programming, well, that's not a coincidence!

The point of monads is abstracting away the structure of the above program from what actually happens. So the very same program above can be interpreted in different settings:

  • for example, the actions can throw an error. In that case, you want to stop the execution

  • or actions can return multiple results. In that case, you want to compute all possible combinations

  • or the actions can read and modify some internal state

  • or the actions can write to some logfile

  • or actions can throw exceptions, and you can catch them somewhere else

  • or maybe the variables are not really values, but probability distributions?

  • or the actions are pieces of a parser, and return the value they parsed

  • etc etc

The common part of all these is that: actions must be executed in order; that they can return values; and that you can use those values later on. Monads are an interface for anything fitting into that hole.

And the advantage is, again, that the same program can be interpreted in different settings, for example, you can use the exact same program to compute with numbers and with probability distributions. Also, you can control and combine what kind of side-effects you allow.

5

u/ramin-honary-xc Dec 06 '21 edited Dec 06 '21

Monads like Either and Maybe can be useful anywhere, especially when using map, ap, chain, or other operators not discussed in the "Mostly Adequate Guide" but which are used in languages like Haskell (mplus, and monadic throw and catch). But I don't really see any benefit to using monads like State or Cont in non-pure-functional code unless you are really working very hard to make your variables immutable everywhere except in the "main" function of your program.

Monadic function types like State and Cont are useful in a language like Haskell which abolishes mutable variables everywhere except in the IO monad, since with State you can write code that appears to be stateful from the vantage point of anyone using your Haskell API, but which are actually pure under the hood.

Another thing to keep in mind: Haskell performs all kinds of optimizations to make sure the monadic composition incurs little-to-no performance penalty, which does not happen in languages like JavaScript or Python. Also, in my opinion, monadic code in JavaScript and Python really makes the code less readable. I have had the misfortune of maintaining a code base where the original coders went out of their way to use map everywhere, for example map-ping over an array literal rather than just using a foreach loop, and it was just so annoying trying to figure out what the hell they were trying to accomplish when more idiomatic code would have been hundreds of times better.

So if you really just want to learn, and have no illusions about monadic code magically making your JavaScript code base more readable and reliable, I'd recommend writing a little program in Haskell using the Monad Transformer Library, or maybe even implement your own version of the monad transformer library. Implementing Dijkstra's algorithm using a StateT (to keep track of the path distance) lifted into a ContT monad (to break out of a loop when current shortest distance is exceeded) would be a pretty good exercise to really get a handle on how useful Monads can be.

4

u/reifyK Dec 06 '21

They are among the most useful things discovered in the last decades. They capture the idea of "you cannot freely get a value out". Don't worry if this doesn't make much sense, because the concept is extremely generalized.

Btw, the idea of "you cannot freely put a value inside" is captured by comonads, which are the dual of monads.

Now if a means is useful doesn't only depend on the means itself but also on the context. In order to use monads you need a monad-ecosystem, because monads act systemic. You cannot just use it here and there in your code but once a value is wrapped the monadic constraint spreads throughout your codebase.

Hence I'd say you shouldn't use monads in frontend Javascript, because there are neither the tools nor coworkers that can handle them.

3

u/woupiestek Dec 06 '21 edited Dec 20 '21

Fourier Theory is about computing the frequency spectrum of a signal among other things. I taught courses in it to both mathematics and physics students. These courses were completely different. The matheticians learned abstract definitions based on function spaces, and rigorously defined distributions. When an integral showed up in an exercise, the question could easily just be to prove whether it converged using Riemann integration. The physicists, on the other hand, learned a ton of heuristics to compute the integrals for the standard case of real or complex valued functions on Euclidean spaces.

Monads come from a higher level of mathematics than Fourier theory, but unless you run into a exceptionally sadistic interviewer, you probably will naver have to know why a monad is a monoid in the category of endofunctors. The heuristics of programming with monads are useful if you use a language or library that is based on them.

Haskell was designed for lazy evaluation, which creates a challenge for input and output, since the runtime has to be told explicitly which reads and writes are necessary and in which order they should occur. Monads provide a smooth interface to a complex datastructure that can keep track of that kind of information, which is why they are used there.

2

u/contextualMatters Dec 20 '21

The impact on sequencing is probably lost on most folks used to eager language (and shouldn't).

To push further your idea, even in category, a monad can be seen in many different ways and there are many flavors of categorical approaches (say, a monad is a morphism of bicategory, a 3-cells in 2-cat, etc..)

3

u/[deleted] Dec 06 '21

Only if you want to learn a language where they're a central abstraction, like Haskell. They are not actually that useful in their own right. They are so general that they can only enable fairly trivial functionality.

2

u/nmarshall23 Dec 06 '21

I suggest that you learn FP using haskell.

Follow along on learnyouahaskell.com, use haskell to solve pure math problems from projecteuler.net.

2

u/gaverhae Dec 12 '21

I'll throw my hat in the ring.

The answer to your question is: it really boils down to how much you care about purity. There's a whole spectrum of what "functional programming" might mean, from "try to make functions that return something instead of just changing variables" all the way up to "never mutate anything ever", with "use first-class functions where possible" somewhere along that line.

Ultimately, monads are a technique that lets you pretend you have mutations (and other side effects) without actually having them. What that means is that, if you do have mutation (/ side effects), you'll most likely never feel the need for monads. Which is not quite the same thing as saying they wouldn't be useful; it's just that you're unlikely to ever encounter a problem where you feel stuck and monads are the only solution.

The Maybe monad is not a great example because it's pretty easy to simulate it (/ work around not having it), from Ruby's tap to Clojure's some-> to so-called "elvis" operators. The Either monad is similarly most often easy to replace with exceptions. So let's look at something else.

Say you need to walk down a tree while keeping track of some state. To make it concrete, we'll say you're trying to decorate a tree by adding to each node its index from a depth-first, left-to-right, bottom-first traversal (i.e. index 0 is the left-most leaf, index 1 is its first sibling, etc.). There are a few ways you could go about that (fair warning: none of that code has been tested; for illustration purposes only):

  • You're happy mutating your tree and your counter. You write a function process_tree that takes a node and returns nothing; it walks down the tree, mutating the current node and the counter on each call. That works fine.

    (defn process-tree! [^Node n]
      (let [counter (atom -1)
            process-node (fn rec [^Node n]
                           (doall (map process-node (.getChildren n)))
                           (.setIndex n (swap! counter inc)))]
        (process-node n)
        nil))
  • You don't want to mutate the tree (say you're in Clojure and it's made up of immutable data structures), but you're OK mutating the counter. Your function signature now returns a new node, having updated the counter. On every node, you need to reconstruct a new node based on the new values received.

    (defn process-tree [t]
      (let [counter (atom -1)
            process-node (fn process-node [{:keys [children] :as n}]
                           ;; note: order matters a lot here, Clojure args
                           ;; are evaluated left-to-right
                           (assoc n
                                  :children (mapv process-node children)
                                  :index (swap! counter inc)))]
        (process-node t))
  • You don't want to have any mutation. Therefore, you need to keep track of your index as you move down the tree, as an additional argument and additional return value.

    (defn process-tree [t]
      (let [process-node (fn process-node [node idx]
                           (let [[children idx]
                                 (reduce (fn [[children idx] child]
                                           (let [[new-child new-idx]
                                                 (process-node child idx)]
                                             [(conj children new-child)
                                              new-idx]))
                                         [[] idx]
                                         (:children node))]
                             [(assoc node :children children
                                          :index idx)
                              (inc idx)]))]
        (first (process-node t 0))))

So, how much do you care about immutability? If you're happy with some mutation, as most non-Haskell developers are, you're probably thinking the second solution there is just fine and you can bear having one, completely local, safe, encapsulated bit of mutable state.

But if you're on a holy war against side-effects, or you're programming in Haskell and you simply do not have mutation as an option, you may be looking at that third bit of code thinking "Man, why does it have to be so complicated? I just want to count some nodes."

And that's where monads can help. Monads get a bit ugly without syntactic support, but ultimately, they're a programming technique that lets you write the third code sample above in a way that looks a lot like the second one.

Once you do know monads, you'll start seeing a lot more applications for them, but these are usually better ways to do things you don't really feel pain from otherwise. In a "you don't know it's possible to do better" kind of way, just like most programmers who've never heard of first-class functions don't feel the pain of writing for loops all the time.

If you're still thinking monads are worth a shot, I've written a blog post explaining monads as a programming technique for a Clojure audience. I've not personally found much practical use for all the category theory around them; it's nice to know the laws are grounded in solid theory, but you don't need to understand that theory to understand the laws or to use them in practice.

3

u/yawaramin Dec 06 '21

Monads are not an essential element of functional programming. They get billed as some super-important concept because Haskell is the biggest fish in the FP pond and also because they’re kinda cool and people want to look cool by using them.

The essence of functional programming is:

  • Keeping most of your code decoupled into pure functions and pushing out impure functions to the furthest possible layer of the program

  • Expression-oriented programming, i.e. programming by composing together expressions instead of using statements

  • Abstracting over logic using higher-order functions

  • Related to that, understanding currying and partial application

  • Recursion with tail-call optimization which enables you to express loops as just function calls, and make it super efficient

Those are the key aspects. But I think to get the most possible benefit from FP you do need a strongly statically typed language. JavaScript can be used to apply some aspects but it’s awkward and bolted on. TypeScript goes further but it has some issues which prevent a natural fit. Imho it’s really worth it to learn an ML to really get what it’s all about and how neat it is. Check out this free online course, even if all you do is watch the lectures: https://www.coursera.org/learn/programming-languages

About monads—yes, they are useful. But people talk about the Maybe monad, the Either monad, etc. and misunderstand something basic. These data types themselves are not monads. They are just data. They can be made to behave like monads by implementing the required operations for them. Think of ‘monad’ as an interface which different data types can implement.

It’s not important to talk about the concept of ‘monad’, at least for beginners. It’s more important to understand how the different types behave like monads—List, Either, Maybe, IO etc. But that comes after the more basic understanding of the syntax and semantics of a proper functional programming language, which is where I recommend people should start.

2

u/reifyK Dec 06 '21

Keeping most of your code decoupled into pure functions and pushing out impure functions to the furthest possible layer of the program

If you try doing this you'll end up with something similar to a monad. Giving it a uniform API and some laws to comply to you can officially call it one.

2

u/yawaramin Dec 06 '21

Ending up with ‘something similar to a monad’ is not a foregone conclusion though. If architected as I mentioned, a program can be split into layers where the code wouldn’t really look like monadic style. I just would caution against jumping to the idea ‘I’m going to need monads for my application, so let’s go down the Category Theory rabbit hole’.

2

u/peanutbutterwnutella Dec 06 '21

it takes time; it’s not feasible to read a book on FP and start developing apps in a different paradigm without some roadblocks. it took me months just to build something simple.

the thing is, it will definitely pay off