“A monad(3) is a monoid(4) in the category(see 1) of endofunctors(5)” (1)A category is the prime structure in category theory(see 2). (2)category theory is a ways of connecting vague mathematical concepts by similar structures of objects from these different theories/concepts. A collection of such connections between objects (and the objects themselves) may be called a category(see 1). (3)A monad can be easily(6) followed on from (1) (2). (4)A monoid can easily(6) be followed on from (1) (2). (5)Blumming magic. (6)10-15 different steps atleast.
My university professor in my cs "functional programming" class just said this regarding monads: "We won´t try to explain monads in this course because frankly, I don´t really know how they work"
There should be way to get refund on your course fee if the prof doesn't deliver. Now as it stands, we pay whether we're getting value from the prof or not
The wikipedia page on monads has the following warning tag... "This article needs attention from an expert on the subject. The specific problem is: article fails to succinctly explain the topic and excessively relies on references to Haskell-specific terminology, ideas and examples." Which is pretty much the problem with this video.
A monad is a thing that does things. Look it can trimt and flavon and wombnat and you can use then to arrange things, unless you can't. Perfectly clear.
Yeah the "don't worry if you don't know Haskell" is incorrect. The difficulty in teaching is it's difficult to gauge how well you're explaining something to people who don't already understand. I've read a lot of far better explanations of monads but because I know F# rather than Haskell I didn't really follow this one since the last few steps were just "unexplained syntax magic happens here".
When a programmer says 'this piece of code cannot fail' he invokes a principle even deeper than logic or mathematics, guaranteeing that if the program is ever used as part of a critically important system, it will fail in a way never even contemplated, and destroy the whole system in the process.
@@GregoryMcCarthy123 The point is that computer failures unrelated to programming can change the infallibility of proven programming (sometimes by literally changing the program). One of the reasons that some mission critical systems are multiple redundant and voting. (Ignoring a discussion of the robustness of the vote collector.)
@@edwardmacnab354 store a single variable 10 times in different parts of memory/hard drive, whenever one of them changes, change it to the value in other memories
I feel like I just watched a magician perform a trick. I was following along with a simple set of refactors to deal with a series of problems, all things that were (despite the syntax) simple and obvious, until suddenly he reveals, "Surprise, we just made a monad." And now I'm left wondering to myself: at what point did we make a monad? Why is Maybe a monad? What are the characteristics that make it a monad? And how is this different from whatever else you would normally do in this language. Maybe the difference would have been more obvious if I knew the rest of Haskell, but I feel like an English speaker learning about mathematics in French. To make matters worse, he then talks about its importance in allowing for side effects in functional languages. But his example didn't have any side effects; it was itself purely functional. So how does this lead to handling side effects? I think this would have been easier to understand in a three act structure: start abstract, specialize it to something concrete, and then generalize it back out to the abstract. First, lay out what a monad is in theory: its purpose, shape, characteristics, and effects. Then go into a concrete example (like he did) showing how it works in practice, filling in the general form of the monad with a specific implementation. Finally, generalize back up to the abstract by showing how the parts of the implementation could be varied to accomplish a wide-variety of different effects. Instead, he started with the example, didn't do enough to outline what part of that example was based on the abstract concept, and then jumped into the fully abstract without demonstrating how one goes from the concrete to the abstract. This has taken me from knowing nothing about monads to believing that monads are complicated because I couldn't even follow what was presented as a simple example, and I've been a professional programmer for over a decade.
_"at what point did we make a monad? Why is Maybe a monad? What are the characteristics that make it a monad?"_ maybe you know all this already; I don't know if this will help, but here goes: a monad is *_three_* things *_together:_* 1. *_some data in a wrapper_* one explanation I saw in a tutorial for one of the python libraries was, "a monad is just a tuple", and (while it's actually just 1/3 of a monad) this point is what they meant. it doesn't have to be a tuple, but that's one way to represent it. in the video, this was what he was talking about when mentioned type constructors, because types are how Haskell represents it. one way seen it done in Python is with an object-the object wraps the data. you might have, for example: class Failure(): self.value = 9 self.failed = False 2. *_something to wrap the data up_* in the python object example this would be the dunder init: it creates the instance and stores the data inside the wrapper. this is the 'return' he was talking about; it's also called 'unit'. you might have something like: def \_\_init\_\_(self, value, failed=False): self.value = value self.failed = failed 3. *_something to apply a function that works on the_* value *_to the_* whole monad this is bind, >>=. in the Python object example, bind might look like: def bind(self, f): if self.failed: return self else: try: x = f(self.data) return Failure(x) except: return Failure(None, True) so: Failure("9").bind(int).bind(partial(operator.mul, 2).value # "18", no problem Failure("dog").bind(int).bind(partial(operator.mul, 2).value # None, but no problem from trying to multiply it by 2-it never got there *the point is that bind abstracts out the part where you have to unwrap the data before you can **_do_** something with it.* this is analogous to how map or reduce factor the looping out of various tasks.
@@thoperSought Thank you very much. This translation into Python really helps. I guess the >>= notation is the part that was the most confusing for me in the video. Could you please by any chance produce a similar example with demonstration of how monads could be used to isolate side-effects? I have just seen a video regarding FP that focused on Clojure implementation and they hinted use of side-effect queues which is an approach that I can understand and atoms which are just pure state containers similar to state vectors in control theory. So I wonder what Haskell does differently there.
My favorite definition is "A programmable semicolon." I like this because it shows that a Monad can help chain together operations. The usual ; just does "nothing" but if you program it, you can tell it to check whether a program failed, log to a file, or anything else you might want to do.
If that is what it is, then you just gave one of the best definitions I could ever imagine, because in those few words I feel like I understand exactly what you mean; unlike this 20 minute video.
@@robbiedozier2840 kind of. The with... as... In Python is setting up a nice little box in which you know something (usually a file being open) holds, and outside of that box, you don't have to worry since everything is handled with closing the file, or whatever. A monad is kind of like having a "with .. as" for every line of code. In that sense it's more general, but your intuition is correct.
Asking what is a monad is similar, in a sense, to asking what a vector space is. It is a collection of objects related by operations and a few rules. In the case of vector spaces, the objects are vectors and the operations are vector addition and scalar multiplication. The rules are that these operations are closed and follow rules of linear combination. For monads (from a programming POV), the objects are type constructor functions. The operation is just one, function composition. The rules are that there is a unity function, that when composed with other constructor, returns the same one as if the composition was never done. And that function composition is associative (no need to use parenthesis to specify order of composition). That is it.
Haskell programmer here for the lols. You never understand monads, you just get used to them. Until you understand them. Then you realize you've fused with the machines.
To me a monad is just the pattern of having a method for sequencing indefinitely and a method for what to do once you hit the bedrock of your sequence. For example, if you are processing a list you need a method for navigating the list sequentially and then a method for what to do once youve reach the end of the list.
Checkout the 'Functional Program Design in Scala' on Coursera, where the Monad is mentioned in First week. I think it has a pretty nature explanation (but not as complete as the HaskellWiki as it is still understandable)
Monad = a special kind of a "design pattern" in functional programming that allows writing code generically In terms of the video, the term "monad" explained via an example of "maybe monad" design pattern. It shows how a program can be simplified AND allows us to see what "writing code generically" means (e.g. avoid common error checking). Though, in order to truly achieve "writing code generically" it's not enough to have only "maybe monad" and that is why there are exist other monads. The video doesn't show other examples of monads but we can assume that a monad is a "design pattern". But it's "a special kind" of a design pattern, not a generic one. To summarize, knowing what "desing pattern", "a special kind" and "writing code generically" means we should be able to understand what a monad is.
@@scubed4328 Right, that's really not that hard. And with this knowledge one can even build simple monads, eg if the functor L is left adjoint to R, then RL is a monad and LR is a comonad.
The beautiful thing about Monads when it comes to computing is that so many people fail to consciously understand what a Monad is but yet their code shows they develop an unconscious understanding of it out of necessity (for optimization and simplification of code). They may not implement Monads explicitly but just about everyone does so implicitly without realizing they are writing the same code over and over again. I honestly think this is why the idea of generalization and support for generalizing functions has become such a huge deal in recent years. Maybe it's just that I've been exposed to it so much that I notice it more now but it seems like in the past generalization via Monad-like patterns was more the realm of grey beards while now it's become an intermediate level skill.
People who have problems with monads are those who are in-between -- i.e., those that have not programmed that often or have not learned modern programming concepts as exposed by Haskell. Long-term C developers can build monadic functions on their own. In fact some may pull examples from their own projects without realizing that they were using such functions.
Absolutely. Rust basically has monads, but not under a consistent heading. Option and Result (Maybe and Either) have and_then functions which act exactly like monadic bind. They also both implement ToIterator after which you can use flat_map, which is _also_ monadic bind.
...which only goes to highlight that we are failing to explain them properly. If it's a concept that pretty much anyone can get their head round, why can't we explain them to each other in a way that's easy to get your head round?
If you're still wondering how on earth monads are useful, reflect on that bit where he said _"This is a bridge between the pure and impure world"_ . Monads - among other things - allow you to explicitly separate code that doesn't have side effects and code that does. Furthermore, in a pure functional programming language you code in such a manner that mixing impure and pure functions by accident is *_actually_* *_impossible_* . Such restrictions might sound harsh, but it saves you a lot of time of debugging for runtime errors and is of utmost importance for functional languages, for they're completely built upon the notion of modularity in terms of functions. In Haskell you always *_know_* which sections of your code are tainted by functions that *_might_* have some weird side effect, and a code that actually compiles is more likely to work correctly than on the first try than most mainstream languages, thanks to the draconian type system. There's more to Monads than one can grasp from a 20 minutes video - or a 10 lines comment for that matter, but don't underestimate the notion. Personally I've never employed functional programming in any big personal project, besides some tinkering here and there, but acquainting myself with it has improved my reasoning about problems in general. You'll deal much better with recursion after learning some basic Haskell, for instance.
I don't know if this helps anyone, but I use shipping/transportation as analogy when thinking about monads. Just like you can have many different types of vehicles (cars, trucks, boats, planes, ...) you can have many different types of monads. Each vehicle is different in their own way, but in general, their purpose is to transport items from point a to point b. When shopping online, you don't necessarily care how the item gets to you, as long as you receive the item you were expecting. The infrastructure in place allows you to do this. In the same sense, programming with monads gives you the ability to process data without caring about how it gets to you or what side effects result from "transporting" the data. The power of monads comes from the ability to connect the methods of "transportation" together like Lego to build a complex infrastructure from smaller parts. I think a lot of the confusion around monads comes from the fact that many introductions try to explain how to design the "vehicles" without explaining why they are useful in the first place; and this leads people to believe that monads are too complex to be useful.
This is one more explanation of monads that does not tell you what is a monad. There is a reason why I like and dislike monads, and that is because any competent programmer knows them, but they probably did not learn them under the name "monad".
Well, there's no need to complain in that case, because if you're style of coding is just writing things on your screen, then you're not going to get an output regardless.
It explained the idea perfectly, it's all about the pattern that various effects could happen in a sequence of computations and still you want to "plug" those computations to play nicely together even though the types do not match, that is a monad.
I think that the problem of using "maybe" as the canonical example is that it obscures what is meant by an "effect". Any language that supports unthrown exceptions will trivially handle this example as a pure function. This video makes monads seem like syntactic sugar for a language defect; and thus fails to illuminate. Examples that use IO make the impurity unavoidable, and therefore less obfuscated
Once you already have a hint about what monads are and you have at least a bit of functional programming experience this becomes a really great summary. Great work, thank you.
From what I can gather from the comments, a monad is like a container class that encapsulates multiple types, so that (for example) you can have a function that returns one of multiple types. The example here is exception handling. The reason exception handling is weird in Haskell is because it's a "pure" functional language, so functions in Haskell must be like mathematical functions: each input maps to one and only one output, and cannot have side effects (such a global variable manipulation). Exceptions ARE side effects, so they've been thrown out. Instead, you write functions that return either a value or an error. The reason you might want to do this is that it makes your program much more deterministic. The programmer is forced to deal with the effects of errors instead of simply trying to ignore them (or even being unaware of how exceptions are handled in a function he's calling). Meanwhile, people reading the program can see the error handling much more explicitly... and elegantly, since the syntax mostly stays out of the way of readability. It looks like a _very_ elegant solution (which is apparently being adopted by mainstream languages)... I'm sorry to the gentleman in the video, but unfortunately he fails to explain it properly. Even the comments are doing a better job.
The summary in the first sentence is a bit off target; the first part describes a type class (which Monad is; another example is Num for numeric, which contains arithmetic operations), and the second part is already enabled by sum types holding fields (which Maybe is; so is Either, and both have instances of Monad). But neither describes the concept of a monad. The prelude describes it thusly: "it is best to think of a monad as an abstract datatype of actions". A monad in Haskell provides a way to sequence processing steps; they could pass information from one to the next, return information, be skipped, repeated, or even reordered. For instance, the STM monad (which allows shared mutable state in multithreaded programs without locking) can repeat actions which it determines need to be retried, and the Maybe monad can skip actions it determines receive no input. The IO monad is the most flexible, as it can perform anything at all, including non-deterministic behaviour; it is also isolated, in that the only thing that performs IO actions is the main function. In effect, the main function's job is to produce the sequence of actions that shall be performed. The Either monad can be easily applied as exceptions are, in that it carries information down the fast Left path as well as the thorough Right path, and the Control.Exception module contains support for translating between this form and IO monad exceptions. Many monads do much simpler work; for instance Identity, First, Last, Max, Min, List (called simply [] in the library), Product and Sum. These are used to take the same internal steps and produce different results from them. State provides a way to carry data past steps, so the steps themselves don't need to forward all state. All of these are deterministic and polymorphic.
The example was how a monad could use used to handle failure, but monads themselves are really about encapsulating the glue that holds a set of sequential steps together. For example, the list monad allows you to write a sequence of steps that are performed for each item in the list, or for pairs/triplets of items in multiple lists; all without writing explicit nested loop code.
Not really. Nomad is a tool that geeks who do not understand input and output use to pretend that input and output is non-existent it their programs, while at the same time performing input and output.
Considering that there is a monad literally called IO which is used to do Input and Output and that monads are used for more than I/O, I do not think saying it is a misunderstanding is either clever or funny.
There's only one problem: Haskell has exceptions that can occur in seemingly pure code. For example: div takes 2 ints and returns an int. What happens when the second parameter is 0? An exception!
The problem with most explanations of Monad is that they're either too dependent on mathematical understanding of category theory, or too concrete, too in-the-weeds. People fail to explain the concept in an abstract way without reaching into hard-to-relate mathematics. This explanation in particular is too concrete and missed the "why?", the big picture.
All this video is kind of a "why". If it was a proper "what", he should have explained SemiGroups, Monoids, Functors, and Endofunctors... Actually he showed the Maybe Monad as an Endofunctor (he didn't say anything about the >>= associative properties)
Any time you write a function that does impure things (btw impurity doesn't just mean side effects, a function that can potentially return an exception is also impure), then you can't just pass in concrete values. You need to wrap it in a nice (Maybe) box, such that during the chain of operations, we have someplace to tuck in the error-info when something doesn't go as planned. The boxes have compartments for error (or Nothing) info. While this box idea is nice, unfortunately, now your code needs to be aware of this box and should know how to handle the box and its contents. So, people ended up writing a lot of (noisy) code (8:45). Monads provides a nice abstraction over these type of code. What are the things that you do with the box 1. Put something into the box (return) 2. Check the box, take the value out and apply a function (thereby transform the value), put the result back into the box (>>= bind). Monad is a kind of like a specification. For boxes who wants to be Monads, they should provide support for the operations as in the specification. The boxes Maybe, IO, etc does that.
Imagine watching someone explaining some useful mechanical device for half an hour. You learn that it can enable one human to, almost effortlessly, move objects that are far heavier than what one would expect an average human to be able to move at all. Not even just that - people are able to move the objects over quite long distances and there are reports that they can sustain that work for many hours. From what you hear, the device is not overly complex: however, and not many people realize that, this is a result of optimization techniques that have been in development for decades if not centuries, and recently rediscovered. That's pretty much me sitting here at the end and saying "you mean a wheelbarrow?!" @Computerphile: not being mean, just a perspective from a long time programmer facing the new terminology:)
@@nunyabiz2016 And you missed mine. How am I, a layperson, supposed to read that paragraph and guess that he means a wheelbarrow, when it could apply to all sorts of ancient inventions? It could be a cart, a hand pump, a crane, or a catapult. Maybe I, a novice programmer, already know what monads are, but I don't know that I know it, because Professor Hutton didn't describe them in a helpful way.
LOL AMEN! In Java, for int division by zero, you really have no choice but to throw an ArithmeticException because the result cannot be valid. It is undefined, but int variables can’t deal with that. For floats or doubles, the divide-by-zero result would be NaN (or maybe Infinity), and the calling code would need to check for that. FUN! 😒
@Matthew And googling brought up this video. Are you just saying to look at another resource because it may be more helpful, because if so, that's kind of the point of their comment.
(M, T -> M) -> M This is a monad basically where M is a type constructor with one type parameter. Then we got a function which takes M and another function T -> M, where the first function then returns M so it can essentially be seen as a wrapper. Hope it helps!
It's just weird looking algebra with a bit of extra notation (the :: "has type" syntax). My uni does a discrete maths course that uses pseudo-Haskell, and a lot of people complained that they needed to know Haskell. I understand the intuitive complaint. It needs to be better explained how it's exactly like things you already learned early on in secondary.
@@holonholon1141 I think you misunderstand the complaint. You need to already understand the underlying *meaning* and *idea*, which is kinda weird and alien to most people. The syntax is secondary.
Monad = a generic function that is applied to a pattern (sequence) that returns a wrapped type. Always returns same output type for input type Pure Int -> Monad String -> Monad VS Impure Int -> Int | undefined
If you're a Java programmer and think you'll never see this in the real world then you might be surprised. If you're using the nice Optional type that comes with Java 8 then you're using monads. The Optional.of() function is equivalent to 'return' in the Maybe example and Optional.flatMap() is equivalent to the '>>=' sequencing operator. Understanding that made the whole concept of monads finally 'click' for me.
A freakin' men. I love haskell, but more explanations need to show examples of these concepts in the more commonly used languages. Just to bounce off of this, if you're in C#, then it's worth noting that IEnumerable is also a monad. "SelectMany" is the same as ">>=". I think that javascript's promises are another example of a monad. I believe then() is the monadic bind operator.
Meh. I believe I roughly understand the concept of monads, and I still think it's mostly useless for real world applications. People can manipulate optional types, promises, observables and exceptions without ever having to wrap their head around ">>= : m a -> (m a -> b) -> m b". In 99% of real-world cases, developers only need "a ?? b" and "a?.b", and the mathematical background is useless.
I've been learning Haskell for some time while being only briefly exposed to Java. But calling them "Optional.of()" and "Optional.flatMap()" rather than "return" and ">>=" makes the concept so much easier for me to understand. Another proof that naming is the hardest problem in computer science, I guess.
My explanation: monads are a mechanism to implement dynamic overloading of function composition. Suppose you had a set of functions with given return types, and you wish to add functionality when composing them (ie calling each one from the other) but want to avoid going into the libraries of the functions to alter them statically (eg their return types). Monads give you a way to do this. Thus, you can sit at the top level of your program and, without going into the library code, add functionality which lets you access, and act upon, intermediate results mid-way through the chain of function invocations (eg divide by zero), or pass along additional variables (like a log), and otherwise introduce side effects (like printing intermediate values) in an otherwise purely functional calculation in which you don't normally have access to them. It's extremely powerful, since it can be done dynamically by effectively decorating the live functions. The base functions remain intact, and you get to add side-car calculations that are triggered as the chained composition proceeds.
It's too bad his explanation depends on knowing Haskell types, and programming in general. The monad idea can be used in lots of places, anywhere you can think of the problem as category theory categories. Monad is a relationship between two data types, in this case "a" and "Maybe a", such that any functions that work on "a" will work on "Maybe a", where "Maybe" is a concrete monad. Monad laws further prescribe that performing these functions in sequence on "Maybe a" must be effectively the same as when performed on "a". We can think of "Maybe" as a kind of box, then, where the box is the "extra" stuff non directly related to the only value we want to think about - the box idea is where the stuff we don't want to think about accumulates.
Actually my description, analagous to a box, is functor, but monad is not unrelated. A monad just adds a way of changing a boxed value by applying a function returning the same kind of box. Functor, applicative, and monad are all lawful ways of creating, modifying, and combining these "boxed" values.
This video lacks the basic explanation of and definition of the monad. The key to a concept like this is to be able to express it succinctly and not have to elude to it via examples. I am going to state my definition or a Monad here and anyone who agrees just like the comment or comment on it. A monad, is an evaluation that 1) allows any type of input to be entered 2)makes an evaluation as to if the data makes sense in the context at hand 3) converts the data into a context that CAN be used if possible, or if conversion to a useable data type is not possible halts the data from undergoing further evaluation by the program.
If you all don't like the Maybe monad, how about the List monad? List's return is just creating a new List of 1 element (ie return x = [x]) List's flatMap (or bind operator, or >>=) is just apply a function returning a List to each element of the List and concatenate the results. Monads are everywhere. The purpose of them is more abstract. Monads are well-established mathematical objects and because of this you can use their mathematical properties (assuming you don't use side effects). For instance, associativity.
The title of the video is "What is a monad?", but it should be "Some Haskell for people who already understand Haskell and don't mind if I am a bit careless with my english while I give a Haskell example that happens to touch on just one type of monad, but don't explain what is monadic about it - oh and a plug for my book"
richtourist I don't understand Haskell, what I know about FP is some untyped lambda calculus basics, a few days of practicing in Scala and one day of practicing in Scheme to this day, but I still understand this video.
Math: Here is the definition. Let's do some examples. Computer Science: Today's lesson is about this word. Instead of defining it, let's do something else for 40 minutes. Then let's define it at the end and see if you were paying attention.
It would have been nice if the camera kept showing the pages during the explanation. Every time the camers flips to the speaker, one has to switch to visual memory to try keep in mind what's on paper. Thanks.
Same reaction here -- frustrating to watch as the camera keeps switching away from the material, right as you try to absorb it. Also not a great viewing angle -- hard to make out the Haskell symbols at 360p.
I really didn't like the way this was explained. It was too complex for someone new to functional programming and Haskell, and it really didn't show how powerful monads can be. Another 10 minutes and a slightly more advanced example modeling a real-world problem with the Either monad would have been a lot better imo.
True but he's not wrong, there are a lot of people who simply don't and can't understand the point of and even the meaning of monads here. We certainly could use a longer video
+Shin Kansen There's a rule in the development of anything, be it TH-cam, game dev, or writing: your audience knows what's wrong, and you know how to fix it. Maybe I'm wrong, and that longer video would have been terrible, but I know that the current way of doing it didn't quite work for me (and looking at other comments, it didn't work for a lot of others either). The best of the talks I've watched to understand monads took around 30 minutes and explained them using real-world situations (eg. database querying for an android app in Scala), and I believe that taking a few of their ideas would help, as it worked a lot better for me and many others.
So, we were shown an example of monad, we were told what they can be used for. But never actually explained what is it. That’s not how explanations supposed to work, aren’t they?
I'm going to give a layman's interpretation of what a monad is by describing the actual purpose of a monad instead of a specific implementation. A monad allows you to take some type, Int for example, then performs some operations/functions on it that might fail while also not producing side effects (anything that changes the state outside the function itself). So for example Java would throw an exception for 1/0, but that's a side effect and functional languages are defined by the absence of side effects as much as possible. Java Optional is an example of this kind of pattern: don't fail, propagate the error to the caller. Another component is that Monads allow you to mix functions that take Int with Optional without doing Optional everywhere on everything, which would be verbose and ugly. If you have to deal with sync/async functions interacting you know the pain of this type. So there's multiple levels of producing no side effects at play here: program runtime and the structure of code itself. tl;dr Monads allow error handling in a no side-effect way by propagating errors up to the caller while also allowing you to use other functions that don't require error handling (think Int vs Optional in java).
An extremely long prelude which assumes a lot of knowledge and introduces lots of unexplained items so that one is led out into the quicksand and left to sink in a sea of new questions. One's fear of monads and the impossibility of understanding them increases.
Worth noting that the Maybe monad is a core concept in Rust as well, except it's called Option, and Just/Nothing are Some/None respectively. Other monadic types can be implemented with traits.
"So Monads are a concept that was invented in mathematics in the 1960s" And here I thought Leibniz was from the 18th century.
7 ปีที่แล้ว +42
This was a bad video about monads because the guest professor only speaks in terms of Haskell the entire time and never gives a conceptual overlook on what monads actually are. That besides the fact that he keeps talking about concepts he never properly introduced and other smaller problems.
There isn't one thing Monads are, outside of the "bind" (or "join") and "return" (or "pure") operators. Monads are things that support those operations. And there are a LOT of things that are monads. Lists are monads, for example (they model non-determinism). Continuations and callbacks are monads (it's called Cont). Functions themselves are in fact monads. It's kinda hard to stress how fundamental they are to folks.
Romário Rios Also, it's a bad video about Monads because after he spends twenty minutes talking about Haskell he does a "buy my book about Haskell" promotion. Seriously that's the kind of naked capitalism I'd expect from a late night infomercial, not a -phile video.
The Applied Category Theorist in me wants to be angry, but instead I am now resolute on playing this video in front of this weekend's Applied Category Theory #3 conference at UC Riverside to prompt discussion!
"I want to explain this obscure idea, so I'm going to use the most obscure commonplace language I can and never actually say 'this is the thing'". The hell's a monad?
GTG3000 i thought he explained it pretty well, if you didn’t understand this maybe you should start learning about some of the basics of functional programming before learning about these kinds of things?
The video was easy to follow, and I think I understood the concept of a *Maybe monad*. The problem is that I've no Idea how to apply monads to wildly different effects. The video should have had examples of those also.
In functional programming, a monad is a mechanism that allows programs written in an otherwise pure functional language to perform impure operations that aren't allowed in the functional paradigm. Each pattern of impure operations has its own specific monad. For example, Professor Hutton's video describes the Maybe monad, which deals with situations where the value may not even exist. The IO monad deals with data that's either inputted from or outputted to a physical device (I/O), and there are other monads that are used for other purposes. In Haskell, monads are implemented as data types. They're called "abstract" data types because their contents can be of any type. The value x in a monad with constructor M is written as "M x". The constructor creates a monad value, i.e. a value inside the monad. The monad acts as a sort of tag or label that keeps the value separated from the functionally pure parts of the program. Internet tutorials variously call it a "spacesuit", "toxic waste dumpster", and other colorful metaphors that imply containment or isolation. Each monad has a function, usually called "bind", that implements the special handling associated with the monad. In Haskell, bind is represented by the operator ">>=". The first argument of bind is a monad value, and the second argument is a function that takes a raw value (not in the monad), tries to calculate something, and then returns its results wrapped back up in the monad again. Bind does whatever impure things it's programmed to do, which may or may not involve the first argument, and then it may or may not extract the value from inside the monad and pass it to the function, depending on whatever the rules for the monad are. In pure functional code, operations can be chained together through function composition, as in y = h(g(f(x))). With monads, bind replaces function application: yM = fM(x) >>= gM >>= hM, where yM is a monad value and fM, gM, and hM are functions that take regular values and return monad values. The impure processing of the monad is handled automagically, and you can use Haskell's "do" notation to make your code even more compact. 🙂
"It's just a monoid in the category of endofunctors" - well, don't laugh at it and try to decode what a monoid, functor, and endofunctor really mean. Functor - is a morphism(i.e. transition, transformation) from one category to another. Endofunctor - morphism from one category to the _same_ category. Monoid consists of following components: 1. A set of objects from a category. 2. A _transitive_ binary operation that can be applied to the objects in the set (like addition for integers). 3. Identity object, that is when used with any other object in a set using given binary operation returns that object. So, a monoid would be a set of all non-negative integers and addition for binary operator with identity element 0. Or set of all positive integers and multiplication operator with identity element being 1. Note, that division or subtraction cannot be used in a monoid, as they are non-transitive.
Joshua Barretto it's not very beginner friendly tho, it is accurate, but unhelpful for someone uninitiated. I recommend Brian Beckman's video on the subject.
Think of monads as pipes in your bash, e.g. echo 1 | program1 | program2. Echo puts stuff into the shell context so you can use it to pipe it (return) and the | is just the >>= operator. Tl;Dr: you use this stuff for sequencing things and you wrap it in a type to do the extra behavior in between (e.g. wait for async things, stop on error).
There are many ways to skin a cat. Graham decided to use an example which is simple enough that you can explain all the details without expecting too much background. This is maybe not so convincing in terms of usefulness but if you are using a real world example you will wave your hands how it is actually done.
I come from the Python world too, and took up Haskell thinking it was just another language. It's not. It's loaded with concepts, and new ways of thinking. Definitely something to look into if you're growth oriented, and your Python code will probably improve vastly too... such is the promise, and I've seen a little of that improvement in my own Python code.
We are not talking about that kind of monad. Completely different concept with the same name. I know you probably know that, I'm just saying it for people who don't know. There something called monad in philosophy. Here we are talking about monad from category theory.
@@Alkis05 Yeah... however, beyond the name, the conceptualization itself remarkably similar. Remember, Leibniz is the one who invented Calculus (I know about the controversy and I just feel like edging it on), and we use more of Leibniz's notation in modern Calculus.
@@Garland41 What calculus has to do with anything? Completely different area of mathematics. lol. Category theory had an independent origin and the concept of monads there grows organically from other entities. It has very little in common with the philosophical concept. As Category theory itself would put it, the characteristics of the concept itself is less important than how it connects and relates to other concepts. And those relations are very different for the two monads.
I learned about Lebnizian metaphysics before touching any computer science, so for me monad as an entity that is independent substance yet in divine coordination with other monads was a natural concept for me. The computer science one is confusing as heck. Why did they use the same word???
If you weren't scared of monads before, you are now! Professor Graham Hutton just made sure of it. By the way, my browser's spell check doesn't know monads either. It suggests gonads or nomads!
A more specific criticism of this video: You lay out a bunch of concepts that are relevant to monads, but you don't (or if you did, I missed it) circle back and *define* monads *in terms of* these concepts... so I might fully understand the concepts, but I still can't pinpoint the answer to "what is a monad?". It's like if you asked "what is addition?", and then go on to talk about collection of items, and combining items to create bigger collections, and.... fail to say that "addition" is "the act of combining" according to those principles. So, I humbly request a follow-up, that both says more specifically what aspects of all of this actually define what a monad is, and also maybe goes into more examples and/or depth in various ways.
@@DavidLindes I'm not sure of the exact time stamp, but the point is that the definition of a monad is that it's the combination of the three things he's explaining *_around_* 16:05
@@thoperSought I stand by my original statement. The pieces have been explained, but the word has not been defined. And as for your attempt at a definition, too much of “the three things he’s explaining around 16:05” are specific to the Maybe monad, so that doesn’t help me understand what a monad _in general_ actually is, really. Thankfully, Wikipedia did _slightly_ better, and I have some idea now. That doesn’t invalidate the critique of the video content, however. (Which I rewatched all of, and still didn’t catch a definition.)
@@DavidLindes so, I def. see where you're coming from-I didn't get it when I originally watched this video, either. otoh, you asked for him to _"circle back and _*_define_*_ monads in terms of these concepts,"_ which I argue that he did. you're right that he did it at 16:44. he laid out the three components Maybe, and then said, _"A monad is some kind of type constructor, ..., together with two functions that have these two types here."_ I would argue that it's not sufficient-that _no_ definition _can_ be sufficient-unless *_you_* have enough background in specific cases to see what the monad factors out. I watched a talk once where the speaker compared some code using fold/reduce with a few similar for loops, and showed how fold was factoring the looping out of the code. map (which you may know can be defined in terms of fold) does the same thing. a monad factors *_something else_* out of code in *_the same way_* that fold factors out the looping. one of the things that makes this really difficult is that the "something else" with monads is harder to pinpoint, and a lot more stuff fits into that slot.
a great example of taking a simple problem and making the solution as complicated as possible. 40 years ago I learned a simple rule divide nothing multiply everything. Surprisingly I dont get division by zero errors.
I like how he just says "We're going to create an expression that can be either a value or a division" and never really makes it clear why we're ONLY doing division here. You realize, halfway through the video, that it's in order to highlight for the "divide by zero" case, but by that point you've been scratching your head for several minutes wondering why division is the only operation we're dealing with. If he'd said at the start "We're going to create a class that can represent mathematical expressions, so it has Value, Add, Subtract, etc etc etc…" AND THEN focused on the division case I feel like that would've helped remove a lot of confusion. Also I still don't really get it tbh. He goes on to say "oh there are a few different types of monads" but I feel like it's critical to know what those monads ARE -- this video just makes it look like glorified error checking.
He doesn't really emphasize it in the video, but the heart and soul of every monad is its bind function (>>=). A monad is any data type that has a bind operator. bind is what implements the defining effects of the monad. Instead of chaining operations with composition, as in y = g(f(x)), you chain impure operations with bind: yM = (M x) >>= h >>= j.
Definition around 16:40 which you can skip to if you already understand Haskell (or OCaml) type annotations. Basically in the Maybe monad, its a constructor (like Maybe) and two functions: "return" which takes a value of type a and returns a new value passed through the constructor (so in this case type/value "a" becomes "Maybe a") and the function (or monadic sequencing operator) which looks like ">>=" that basically allows you to chain operations (that may fail) so it takes a type (Maybe a) and a function which goes from (a to Maybe b) and (finally) returns the Maybe b
Thanks for help saving a lot of time and actually giving an understandable explanation. All the preface was utterly unnecessary imo and I dont even write FP!
@@Ytuserqf Really glad that I could help, reading the comment I wrote again, I think I was smarter then! That makes me a little sad, lol I am getting dumber I guess.
I agree about the use of the math terms (not so much as he argued for it) because as soon as you need to look up the properties, extensions, implications, etc. of "effects" you're immediately going to run into the math terms anyway. Alternatively you can come up with a whole language that's not as "scary" and meticulously rewrite all of category theory, type theory, and so on, but that's adding complexity, not removing it. "Polymorphism" is one of those "scary" terms but nobody bats an eye, even though it's a morphism just like endomorphisms, isomorphisms, and loads of other gifts from category theory. Edit: I DEEPLY regret reading the comments below.
I totally get needing to return Nothing rather than actually dividing by zero. Preempting errors is better (and faster). I do it in my code all the time. So I understand having to create a new safeDiv function that would simply not attempt the division if the second variable was 0. I get passing the values on to another function conditionally. I even get the idea of no longer just returning an integer, but also returning another type that indicates whether the division took place or not. I even get putting those together in a single object, so you have a single output. But then he puts it back into the program, and still has to do a bunch of checks again. And I am completely lost. What's the point of that single object if you still have to check for it? And when he talks about how the program is simpler, it's not. It still contains multiple checks. One check, to test for Nothing and fail makes sense. But two? How does this help? You just jumped straight to nested concepts (which I didn't even realize were nested until the comments told me they were). I still don't know what part of any of this was the monad, whether it's a part I understood or a part I didn't. I also don't know what binding does. Does it just mean sending the variables to another function? Is it just having a function callback? I am left with more questions than answers, I think.
Bindng is really the core magic of Monads, and why we have to define each one uniquely. Let's pretend you have some Context that has a type slot. You've seen Maybe a = Just a | Nothing. But let's ignore the specific context for now. What binding does is take a value with Context, and a function that takes a value and returns a new Context value, and then systematically plumbs that context all the way through. Let's get concrete to help show what that means. Imagine a monad with NO context, "Identity." Identity a = Identity a. Pretty useless except for specialist purposes. But consider it for a second. What does something like this program "do": (Identity 5) >>= \x -> return x + 1 It makes an Identity 6. Now, Identity has 0 context at all, right? So it's really easy. All the bind operator does is pattern match out the number and pass it forwards to the new function. But now think about it, what happens if we used Maybe. We've got 2 cases: (Just 5) >>= \x -> return x + 1 (Nothing) >>= \x -> return x + 1 For the first case, the bind operator's function says, "Oh I have a value. I'll pass that along to the function, and then return what it returns." This is exactly like what the Identity monad did, right? The second case though, the bind operator looks and sees it has a Nothing. "Well dang, I can't even CALL that next function, I have nothing to give it at all. Literally the only thing I could possibly do that would typecheck is return Nothing. I have no other options." I hope this helps explain what binding is and how the program "knows" not to do the extra work of calling forward. Monads are very powerful because they actually model programs that build programs, at runtime. This is fundamentally more awesome than if statements. Let me show you one final (simplified) example. Let's imagine we have an imaginary function httpGet. Its type is Url -> Maybe String (please note, this is not the real world type we'd use and we could never use it, but bear with me for a moment I'm explaining something bigger here). When you need to do 2 of these in one function and use their values, Maybe suddenly makes our life incredibly easy. fetchUserDetails :: String -> Maybe UserRecord fetchUserProfile userName = do userDetails
@@KirinDave Hi there! I know it's been over a year since you posted this comment, but I'd like to thank you regardless. This is honestly the best explanation for monads I've ever heard. I've been struggling with the concept for a while and I finally get how straightforward it is now. Thanks!
So “maybe monad” is basically for “managing unwanted effects” of side effects while making them And it is a partial function which has recursion in its definition as I understand Can you generalize/define monad’s general purpose by intoducing purpose and definition of other types of nomads by examples
AugustusPugin I don't think Haskell is a terrible programming language. It is really interesting. Functional programming shows you a different way to think about programming
Watching these videos to prepare for my uni course in functional programming, your book is our curriculum, very fun to be introduced to the topic by the author himself :D
Monads are insanely useful and not THAT unusual. I'm a scala dev, there are a few of us. Many other langs with monadic things in them too. Also, if you think this video didn't make sense or you got impatient you are missing the point. The monad concept is simple but simple is not the same as easy. Have to take a simple example to unpack the concept. In addition, you will only really understand this by playing around with them. Same with all programming really. Seriously it's worth understanding if your language supports this sort of thing. Your code will become simpler and doing things like dealing with exceptions and acceding the db for example becomes an order of magnitude simpler to manage,read and reason about. Don't miss out.
what I understand is that a monad is like a wrapper for a value that could no be there, at least the Maybe monad that is used as example, like a Promise in javascript. So instead of getting the value or an error, instead you get a thing that gives you the value if the operation worked, and nothing if the operation went wrong (instead of thowing an error at you)
The issue is that if I am anything to go by, people went to the comments to ask what any of this means after finishing. I was at the book recommendation when I scrolled down to see if anyone had an explanation, but I didn't find one. The video is just incredibly bad at teaching anything to someone like me, whether that is because I don't know Haskell or because I don't know what a Monad is in mathematics or whatever else, I don't know.
This is the first accessible explanation of monads I could find. I already knew C# Tasks and JavaScript Promises were similar to monads, and the same for F# Options, but this makes it all clear.
Sounds like a high falutin description of an if function. I'm thinking only professors need to understand jargon coined by professors. For commoners like myself, I'd prefer keeping it simple.
"The problem with monads is that once you know what is, you lose the ability to explain it"
xD
.. but before you gained the knowledge, you did not possess the ability to explain them either, so you did not lost anything ;)
“A monad(3) is a monoid(4) in the category(see 1) of endofunctors(5)”
(1)A category is the prime structure in category theory(see 2).
(2)category theory is a ways of connecting vague mathematical concepts by similar structures of objects from these different theories/concepts. A collection of such connections between objects (and the objects themselves) may be called a category(see 1).
(3)A monad can be easily(6) followed on from (1) (2).
(4)A monoid can easily(6) be followed on from (1) (2).
(5)Blumming magic.
(6)10-15 different steps atleast.
@@imnimbusy2885 what are these?
@@imnimbusy2885 Category, not just a set.
This is a very clear explanation of what a monad is... as long as you already know what a monad is...
And how haskell works
It could be those little birds that keep flying into my window
My university professor in my cs "functional programming" class just said this regarding monads: "We won´t try to explain monads in this course because frankly, I don´t really know how they work"
what a shitty professor
There should be way to get refund on your course fee if the prof doesn't deliver. Now as it stands, we pay whether we're getting value from the prof or not
Aka - the professor is pure and has no effects - aka, useless.
drop out xD
At least they're honest
You have an obstacle. You explain it using Haskell. Now you have two obstacles.
Regex
Before setting out to use Haskell, first dig two graves.
*APL has entered the chat*
Hay! That's my new favorite language your talking about!
It beats ML.
It's between Sunad and Tuesad
too sad. :D
My first thought
At last, a simple explanation that makes sense.
Really.funny 😂😂👏
it's between gonad and nomad
1:52 “Make sure everyone’s on the same page.” *Flips to a different page*
At least he tried explaining what a Monad is, although I doubt that was quite successful
@@theprovidencesalumu Guess that wasn't the right page...
I was already on the next blank page
Came here as I am on the same page as you :D
Which perfectly represented this whole video.
The wikipedia page on monads has the following warning tag...
"This article needs attention from an expert on the subject. The specific problem is: article fails to succinctly explain the topic and excessively relies on references to Haskell-specific terminology, ideas and examples."
Which is pretty much the problem with this video.
A monad is a thing that does things. Look it can trimt and flavon and wombnat and you can use then to arrange things, unless you can't.
Perfectly clear.
@@vendicarkahn4860 Oh! So it's a function?
@@garorobe if not then what is this montard thing?
Yeah the "don't worry if you don't know Haskell" is incorrect.
The difficulty in teaching is it's difficult to gauge how well you're explaining something to people who don't already understand.
I've read a lot of far better explanations of monads but because I know F# rather than Haskell I didn't really follow this one since the last few steps were just "unexplained syntax magic happens here".
So what other functional language actually uses monads except Haskell? None that I've seen...
When a programmer says 'this piece of code cannot fail' he invokes a principle even deeper than logic or mathematics, guaranteeing that if the program is ever used as part of a critically important system, it will fail in a way never even contemplated, and destroy the whole system in the process.
one cosmic ray through a bit cancels all hope in the escape from statistics
Well, that depends on how deeply you believe in mathematics. Monads can be mathematically proven in category theory.
@@GregoryMcCarthy123 The point is that computer failures unrelated to programming can change the infallibility of proven programming (sometimes by literally changing the program). One of the reasons that some mission critical systems are multiple redundant and voting. (Ignoring a discussion of the robustness of the vote collector.)
@@edwardmacnab354 store a single variable 10 times in different parts of memory/hard drive, whenever one of them changes, change it to the value in other memories
@@vadiks20032 management will argue against it calling it redundant . lol
I feel like I just watched a magician perform a trick. I was following along with a simple set of refactors to deal with a series of problems, all things that were (despite the syntax) simple and obvious, until suddenly he reveals, "Surprise, we just made a monad." And now I'm left wondering to myself: at what point did we make a monad? Why is Maybe a monad? What are the characteristics that make it a monad? And how is this different from whatever else you would normally do in this language. Maybe the difference would have been more obvious if I knew the rest of Haskell, but I feel like an English speaker learning about mathematics in French.
To make matters worse, he then talks about its importance in allowing for side effects in functional languages. But his example didn't have any side effects; it was itself purely functional. So how does this lead to handling side effects?
I think this would have been easier to understand in a three act structure: start abstract, specialize it to something concrete, and then generalize it back out to the abstract. First, lay out what a monad is in theory: its purpose, shape, characteristics, and effects. Then go into a concrete example (like he did) showing how it works in practice, filling in the general form of the monad with a specific implementation. Finally, generalize back up to the abstract by showing how the parts of the implementation could be varied to accomplish a wide-variety of different effects.
Instead, he started with the example, didn't do enough to outline what part of that example was based on the abstract concept, and then jumped into the fully abstract without demonstrating how one goes from the concrete to the abstract.
This has taken me from knowing nothing about monads to believing that monads are complicated because I couldn't even follow what was presented as a simple example, and I've been a professional programmer for over a decade.
_"at what point did we make a monad? Why is Maybe a monad? What are the characteristics that make it a monad?"_
maybe you know all this already; I don't know if this will help, but here goes:
a monad is *_three_* things *_together:_*
1. *_some data in a wrapper_*
one explanation I saw in a tutorial for one of the python libraries was, "a monad is just a tuple", and (while it's actually just 1/3 of a monad) this point is what they meant. it doesn't have to be a tuple, but that's one way to represent it. in the video, this was what he was talking about when mentioned type constructors, because types are how Haskell represents it. one way seen it done in Python is with an object-the object wraps the data. you might have, for example:
class Failure():
self.value = 9
self.failed = False
2. *_something to wrap the data up_*
in the python object example this would be the dunder init: it creates the instance and stores the data inside the wrapper. this is the 'return' he was talking about; it's also called 'unit'. you might have something like:
def \_\_init\_\_(self, value, failed=False):
self.value = value
self.failed = failed
3. *_something to apply a function that works on the_* value *_to the_* whole monad
this is bind, >>=.
in the Python object example, bind might look like:
def bind(self, f):
if self.failed:
return self
else:
try:
x = f(self.data)
return Failure(x)
except:
return Failure(None, True)
so:
Failure("9").bind(int).bind(partial(operator.mul, 2).value
# "18", no problem
Failure("dog").bind(int).bind(partial(operator.mul, 2).value
# None, but no problem from trying to multiply it by 2-it never got there
*the point is that bind abstracts out the part where you have to unwrap the data before you can **_do_** something with it.* this is analogous to how map or reduce factor the looping out of various tasks.
@@thoperSought Thank you very much. This translation into Python really helps. I guess the >>= notation is the part that was the most confusing for me in the video.
Could you please by any chance produce a similar example with demonstration of how monads could be used to isolate side-effects? I have just seen a video regarding FP that focused on Clojure implementation and they hinted use of side-effect queues which is an approach that I can understand and atoms which are just pure state containers similar to state vectors in control theory. So I wonder what Haskell does differently there.
@@PterippiGaming The bind operator for a (trivial) logging monad might look something like
LogM x >>= f = print "Calling another function"; f x
@@thoperSought That single comment told me more about "What is a Monad?" than the 21 minutes video I just watched. Thanks!
@@matdryz I wanted to write the same comment. The video is really bad.
The problem with monads is that Haskell programmers were the ones who discovered them first and are trying to explain them.
They were discovered by the pioneers of Category Theory in Mathematics.
You mean the only actual programmers in a field of hobbyists?
You know it's a tough concept when every comment trying to explain it says something completely different.
My favorite definition is "A programmable semicolon." I like this because it shows that a Monad can help chain together operations. The usual ; just does "nothing" but if you program it, you can tell it to check whether a program failed, log to a file, or anything else you might want to do.
so like with... as ...: in python?
If that is what it is, then you just gave one of the best definitions I could ever imagine, because in those few words I feel like I understand exactly what you mean; unlike this 20 minute video.
@@robbiedozier2840 kind of. The with... as... In Python is setting up a nice little box in which you know something (usually a file being open) holds, and outside of that box, you don't have to worry since everything is handled with closing the file, or whatever. A monad is kind of like having a "with .. as" for every line of code. In that sense it's more general, but your intuition is correct.
I like your definition because I can easily understand it, but I have no idea if it's correct.
@@MrBogfrog let me help you. Semicolon is just a >>= operator for datatype which represents state of your program
So what's a monad?
its the .then() js func xd
A monad is a monoid of the class endofunctor.
@@Fingerblasterstudios Show off :)
People should stop saying that. It's not helpful. Then again, I don't think it is supposed to, right?
@@Alkis05 it was something that got burned into my mind somewhere along the way and I only said it to be funny, but I suppose you figured that
It's how many volts in one amper
"A monad is just a monoid in the category of endofunctors what's the problem?"
I just realized I learned enough category theory to finally understand what that means.
Monads are burritos.
Finally some math-friendly, understandable explanation.
a burrito is just a strong monad in the symmetric monoidal category of food
"Category" and "Functor".
Asking what is a monad is similar, in a sense, to asking what a vector space is. It is a collection of objects related by operations and a few rules. In the case of vector spaces, the objects are vectors and the operations are vector addition and scalar multiplication. The rules are that these operations are closed and follow rules of linear combination.
For monads (from a programming POV), the objects are type constructor functions. The operation is just one, function composition. The rules are that there is a unity function, that when composed with other constructor, returns the same one as if the composition was never done. And that function composition is associative (no need to use parenthesis to specify order of composition). That is it.
Haskell programmer here for the lols. You never understand monads, you just get used to them. Until you understand them. Then you realize you've fused with the machines.
When's that point gonna come around? I still manage to get my runtime frozen with monads from time to time
It's well defined in the field of category theory
So like pointers then.
You just say literally: you never understand monad until you understand them. I suppose this is also monad. Right?
To me a monad is just the pattern of having a method for sequencing indefinitely and a method for what to do once you hit the bedrock of your sequence.
For example, if you are processing a list you need a method for navigating the list sequentially and then a method for what to do once youve reach the end of the list.
The rule still stands... "no one can explain monads"
Checkout the 'Functional Program Design in Scala' on Coursera, where the Monad is mentioned in First week. I think it has a pretty nature explanation (but not as complete as the HaskellWiki as it is still understandable)
@@zhy7604 Scala is unbearably tedious though
Monad = a special kind of a "design pattern" in functional programming that allows writing code generically
In terms of the video, the term "monad" explained via an example of "maybe monad" design pattern. It shows how a program can be simplified AND allows us to see what "writing code generically" means (e.g. avoid common error checking). Though, in order to truly achieve "writing code generically" it's not enough to have only "maybe monad" and that is why there are exist other monads. The video doesn't show other examples of monads but we can assume that a monad is a "design pattern". But it's "a special kind" of a design pattern, not a generic one.
To summarize, knowing what "desing pattern", "a special kind" and "writing code generically" means we should be able to understand what a monad is.
it's literally just a monoid in the category of endofunctors
@@scubed4328
Right, that's really not that hard. And with this knowledge one can even build simple monads, eg if the functor L is left adjoint to R, then RL is a monad and LR is a comonad.
The beautiful thing about Monads when it comes to computing is that so many people fail to consciously understand what a Monad is but yet their code shows they develop an unconscious understanding of it out of necessity (for optimization and simplification of code). They may not implement Monads explicitly but just about everyone does so implicitly without realizing they are writing the same code over and over again. I honestly think this is why the idea of generalization and support for generalizing functions has become such a huge deal in recent years. Maybe it's just that I've been exposed to it so much that I notice it more now but it seems like in the past generalization via Monad-like patterns was more the realm of grey beards while now it's become an intermediate level skill.
People who have problems with monads are those who are in-between -- i.e., those that have not programmed that often or have not learned modern programming concepts as exposed by Haskell. Long-term C developers can build monadic functions on their own. In fact some may pull examples from their own projects without realizing that they were using such functions.
Absolutely.
Rust basically has monads, but not under a consistent heading. Option and Result (Maybe and Either) have and_then functions which act exactly like monadic bind. They also both implement ToIterator after which you can use flat_map, which is _also_ monadic bind.
Statement separators are also monadic bind, if you look at them the right way.
...which only goes to highlight that we are failing to explain them properly. If it's a concept that pretty much anyone can get their head round, why can't we explain them to each other in a way that's easy to get your head round?
Keith Gaughan
This fact has led some people, including myself, to refer to monads as "programmable semicolons."
If you're still wondering how on earth monads are useful, reflect on that bit where he said _"This is a bridge between the pure and impure world"_ .
Monads - among other things - allow you to explicitly separate code that doesn't have side effects and code that does. Furthermore, in a pure functional programming language you code in such a manner that mixing impure and pure functions by accident is *_actually_* *_impossible_* .
Such restrictions might sound harsh, but it saves you a lot of time of debugging for runtime errors and is of utmost importance for functional languages, for they're completely built upon the notion of modularity in terms of functions. In Haskell you always *_know_* which sections of your code are tainted by functions that *_might_* have some weird side effect, and a code that actually compiles is more likely to work correctly than on the first try than most mainstream languages, thanks to the draconian type system. There's more to Monads than one can grasp from a 20 minutes video - or a 10 lines comment for that matter, but don't underestimate the notion.
Personally I've never employed functional programming in any big personal project, besides some tinkering here and there, but acquainting myself with it has improved my reasoning about problems in general. You'll deal much better with recursion after learning some basic Haskell, for instance.
So what? There are a bazillion other superior ways to do it.
@@vendicarkahn4860 such as?
I don't know if this helps anyone, but I use shipping/transportation as analogy when thinking about monads. Just like you can have many different types of vehicles (cars, trucks, boats, planes, ...) you can have many different types of monads. Each vehicle is different in their own way, but in general, their purpose is to transport items from point a to point b.
When shopping online, you don't necessarily care how the item gets to you, as long as you receive the item you were expecting. The infrastructure in place allows you to do this. In the same sense, programming with monads gives you the ability to process data without caring about how it gets to you or what side effects result from "transporting" the data. The power of monads comes from the ability to connect the methods of "transportation" together like Lego to build a complex infrastructure from smaller parts.
I think a lot of the confusion around monads comes from the fact that many introductions try to explain how to design the "vehicles" without explaining why they are useful in the first place; and this leads people to believe that monads are too complex to be useful.
This is one more explanation of monads that does not tell you what is a monad.
There is a reason why I like and dislike monads, and that is because any competent programmer knows them, but they probably did not learn them under the name "monad".
Some programmers just write things on the screen without whining that programs should not perform any output.
Well, there's no need to complain in that case, because if you're style of coding is just writing things on your screen, then you're not going to get an output regardless.
*your
It explained the idea perfectly, it's all about the pattern that various effects could happen in a sequence of computations and still you want to "plug" those computations to play nicely together even though the types do not match, that is a monad.
@Shiny: Ever heard of tablets with hand-writing recognition? :p
30 Dage sind ein Monad, ist doch logisch
not in 7 out of 12 months
@@maximalgamingnl9954 Those are monad stacks.
I think most people miss the pun on Tage in a Monat ==> Dage in a Monad :))))
I think that the problem of using "maybe" as the canonical example is that it obscures what is meant by an "effect". Any language that supports unthrown exceptions will trivially handle this example as a pure function. This video makes monads seem like syntactic sugar for a language defect; and thus fails to illuminate. Examples that use IO make the impurity unavoidable, and therefore less obfuscated
I came for the comments. I was not disappointed :D
That makes your comment a recursive one
Remember:
Go was called go specifically so that monads could be called gonads
XDDD
programming language idea: No.
create Nomads
@@sodiboo that'll just give you Nonads
@@sodiboo Nor would give you Nornads.
Now, walk backwards far enough away from the screen so that the rn merges visually to an m, -tah-dah-, Nomads
where's the quote from?
Once you already have a hint about what monads are and you have at least a bit of functional programming experience this becomes a really great summary. Great work, thank you.
thanks for the only positive comment so far
i have a hit what my gonads are. They are highly fuinctional.
From what I can gather from the comments, a monad is like a container class that encapsulates multiple types, so that (for example) you can have a function that returns one of multiple types.
The example here is exception handling. The reason exception handling is weird in Haskell is because it's a "pure" functional language, so functions in Haskell must be like mathematical functions: each input maps to one and only one output, and cannot have side effects (such a global variable manipulation). Exceptions ARE side effects, so they've been thrown out. Instead, you write functions that return either a value or an error.
The reason you might want to do this is that it makes your program much more deterministic. The programmer is forced to deal with the effects of errors instead of simply trying to ignore them (or even being unaware of how exceptions are handled in a function he's calling). Meanwhile, people reading the program can see the error handling much more explicitly... and elegantly, since the syntax mostly stays out of the way of readability.
It looks like a _very_ elegant solution (which is apparently being adopted by mainstream languages)... I'm sorry to the gentleman in the video, but unfortunately he fails to explain it properly. Even the comments are doing a better job.
The summary in the first sentence is a bit off target; the first part describes a type class (which Monad is; another example is Num for numeric, which contains arithmetic operations), and the second part is already enabled by sum types holding fields (which Maybe is; so is Either, and both have instances of Monad). But neither describes the concept of a monad. The prelude describes it thusly: "it is best to think of a monad as an abstract datatype of actions".
A monad in Haskell provides a way to sequence processing steps; they could pass information from one to the next, return information, be skipped, repeated, or even reordered. For instance, the STM monad (which allows shared mutable state in multithreaded programs without locking) can repeat actions which it determines need to be retried, and the Maybe monad can skip actions it determines receive no input. The IO monad is the most flexible, as it can perform anything at all, including non-deterministic behaviour; it is also isolated, in that the only thing that performs IO actions is the main function. In effect, the main function's job is to produce the sequence of actions that shall be performed. The Either monad can be easily applied as exceptions are, in that it carries information down the fast Left path as well as the thorough Right path, and the Control.Exception module contains support for translating between this form and IO monad exceptions.
Many monads do much simpler work; for instance Identity, First, Last, Max, Min, List (called simply [] in the library), Product and Sum. These are used to take the same internal steps and produce different results from them. State provides a way to carry data past steps, so the steps themselves don't need to forward all state. All of these are deterministic and polymorphic.
The example was how a monad could use used to handle failure, but monads themselves are really about encapsulating the glue that holds a set of sequential steps together.
For example, the list monad allows you to write a sequence of steps that are performed for each item in the list, or for pairs/triplets of items in multiple lists; all without writing explicit nested loop code.
Not really. Nomad is a tool that geeks who do not understand input and output use to pretend that input and output is non-existent it their programs, while at the same time performing input and output.
Considering that there is a monad literally called IO which is used to do Input and Output and that monads are used for more than I/O, I do not think saying it is a misunderstanding is either clever or funny.
There's only one problem: Haskell has exceptions that can occur in seemingly pure code.
For example: div takes 2 ints and returns an int. What happens when the second parameter is 0? An exception!
For JavaScrtipt programmers -> The Promise abstraction is Monadic and the Async Await abstraction over Promises is it's the Do Notation.
I just realized that the sharpie sounds aren't actually in sync with the video, my life is a lie
You know, I was thinking of the same thing.
@@Adniwhack so glad someone replied, I felt felt so lonely
And the paper from the 80s !!!
The problem with most explanations of Monad is that they're either too dependent on mathematical understanding of category theory, or too concrete, too in-the-weeds. People fail to explain the concept in an abstract way without reaching into hard-to-relate mathematics.
This explanation in particular is too concrete and missed the "why?", the big picture.
17:10 ...
All this video is kind of a "why".
If it was a proper "what", he should have explained SemiGroups, Monoids, Functors, and Endofunctors...
Actually he showed the Maybe Monad as an Endofunctor (he didn't say anything about the >>= associative properties)
Thanks, @Computerphile, for helping reinforce the idea that you need a degree in category theory to understand Haskell.
Aren't they people that roam from place to place but don't have an actual home as such?
No that's mad.
That's just the dyslexic ones.
Monads ride on calems.
Maybe...
I think they are called Contractors.
Any time you write a function that does impure things (btw impurity doesn't just mean side effects, a function that can potentially return an exception is also impure), then you can't just pass in concrete values. You need to wrap it in a nice (Maybe) box, such that during the chain of operations, we have someplace to tuck in the error-info when something doesn't go as planned. The boxes have compartments for error (or Nothing) info.
While this box idea is nice, unfortunately, now your code needs to be aware of this box and should know how to handle the box and its contents. So, people ended up writing a lot of (noisy) code (8:45). Monads provides a nice abstraction over these type of code. What are the things that you do with the box 1. Put something into the box (return) 2. Check the box, take the value out and apply a function (thereby transform the value), put the result back into the box (>>= bind). Monad is a kind of like a specification. For boxes who wants to be Monads, they should provide support for the operations as in the specification. The boxes Maybe, IO, etc does that.
Exceptions are side effects.
Imagine watching someone explaining some useful mechanical device for half an hour. You learn that it can enable one human to, almost effortlessly, move objects that are far heavier than what one would expect an average human to be able to move at all. Not even just that - people are able to move the objects over quite long distances and there are reports that they can sustain that work for many hours. From what you hear, the device is not overly complex: however, and not many people realize that, this is a result of optimization techniques that have been in development for decades if not centuries, and recently rediscovered.
That's pretty much me sitting here at the end and saying "you mean a wheelbarrow?!"
@Computerphile: not being mean, just a perspective from a long time programmer facing the new terminology:)
That first paragraph could apply to levers in general, not just wheelbarrows.
@@imveryangryitsnotbutter you missed the point genius
@@nunyabiz2016 And you missed mine. How am I, a layperson, supposed to read that paragraph and guess that he means a wheelbarrow, when it could apply to all sorts of ancient inventions? It could be a cart, a hand pump, a crane, or a catapult.
Maybe I, a novice programmer, already know what monads are, but I don't know that I know it, because Professor Hutton didn't describe them in a helpful way.
you meant the round thing right ?
That sounds exactly like the point, he described it in such an obtuse way you aren't supposed to know what he's talking about.
You had one job, Professor.
Admittedly, he failed where all others have failed.
As a Java developer I can say, you don't know what is a verbose code :D
Condolences. :)
@@DavidLindes I also spend a couple of recent years using Scala, so double condolences please.
LOL AMEN!
In Java, for int division by zero, you really have no choice but to throw an ArithmeticException because the result cannot be valid. It is undefined, but int variables can’t deal with that.
For floats or doubles, the divide-by-zero result would be NaN (or maybe Infinity), and the calling code would need to check for that.
FUN! 😒
North Georgia Hawg inbefore 1000’s of stacktraces
@@kencarp57 You can always write your own abstractions on top of primitives
Unless you're familiar with Haskel or already know what Monads are, he may as well be explaining in Klingon while writing in hieroglyphs, how clever
@Matthew And googling brought up this video. Are you just saying to look at another resource because it may be more helpful, because if so, that's kind of the point of their comment.
I've used Haskell before and trust me, Haskell is not the problem here.
@@donwald3436 Well, maybe Haskell is why we don't even understand the problem...
sharpfang How long does it take to pick up a new programming language? Half a day? Get to it.
@@donwald3436 Until you start understanding advanced concepts in it? muuuch longer. Especially concepts absent in other languages you know.
A monad is a monoid in the category of endofunctors
(M, T -> M) -> M
This is a monad basically where M is a type constructor with one type parameter. Then we got a function which takes M and another function T -> M, where the first function then returns M so it can essentially be seen as a wrapper. Hope it helps!
@@capturedflame ok and?
@@capturedflame ok anything else you wanna necro post?
Decent video, but you're high if you think that this is understandable without any previous knowledge of Haskell
It's just weird looking algebra with a bit of extra notation (the :: "has type" syntax). My uni does a discrete maths course that uses pseudo-Haskell, and a lot of people complained that they needed to know Haskell. I understand the intuitive complaint. It needs to be better explained how it's exactly like things you already learned early on in secondary.
Started to look into haskell yesterday. Today this was not that hard.
"It's just weird looking algebra with a bit of extra notation " bruh, that applies for, like ..., the domain of all of Haskell.
@@holonholon1141 I think you misunderstand the complaint. You need to already understand the underlying *meaning* and *idea*, which is kinda weird and alien to most people. The syntax is secondary.
No problem understanding coming from a swift background. If you scratched the surface of functional programming this should make sense.
This was more like an intro to Haskell than explaining Monads well...
Monad = a generic function that is applied to a pattern (sequence) that returns a wrapped type.
Always returns same output type for input type
Pure
Int -> Monad
String -> Monad
VS
Impure
Int -> Int | undefined
"I've gonna implement it with Haskel"
and you just lost me right there
0:54 I like the old school printer paper!
You can tell that he explained monads at least a million times to be this fluent and makes zero mistake...
If you're a Java programmer and think you'll never see this in the real world then you might be surprised. If you're using the nice Optional type that comes with Java 8 then you're using monads. The Optional.of() function is equivalent to 'return' in the Maybe example and Optional.flatMap() is equivalent to the '>>=' sequencing operator. Understanding that made the whole concept of monads finally 'click' for me.
A freakin' men. I love haskell, but more explanations need to show examples of these concepts in the more commonly used languages.
Just to bounce off of this, if you're in C#, then it's worth noting that IEnumerable is also a monad. "SelectMany" is the same as ">>=".
I think that javascript's promises are another example of a monad. I believe then() is the monadic bind operator.
Meh. I believe I roughly understand the concept of monads, and I still think it's mostly useless for real world applications. People can manipulate optional types, promises, observables and exceptions without ever having to wrap their head around ">>= : m a -> (m a -> b) -> m b".
In 99% of real-world cases, developers only need "a ?? b" and "a?.b", and the mathematical background is useless.
@@Olivman7 guess your world is different from mine then :)
I've been learning Haskell for some time while being only briefly exposed to Java. But calling them "Optional.of()" and "Optional.flatMap()" rather than "return" and ">>=" makes the concept so much easier for me to understand.
Another proof that naming is the hardest problem in computer science, I guess.
What about streams in Java 8? Don't they follow monad laws.
2:49 A youtube video just gave me homework :(
That was the easy to understand part of the video. If you can't get past that bit then don't bother with the monad part.
My explanation: monads are a mechanism to implement dynamic overloading of function composition. Suppose you had a set of functions with given return types, and you wish to add functionality when composing them (ie calling each one from the other) but want to avoid going into the libraries of the functions to alter them statically (eg their return types). Monads give you a way to do this. Thus, you can sit at the top level of your program and, without going into the library code, add functionality which lets you access, and act upon, intermediate results mid-way through the chain of function invocations (eg divide by zero), or pass along additional variables (like a log), and otherwise introduce side effects (like printing intermediate values) in an otherwise purely functional calculation in which you don't normally have access to them. It's extremely powerful, since it can be done dynamically by effectively decorating the live functions. The base functions remain intact, and you get to add side-car calculations that are triggered as the chained composition proceeds.
That was more informative in 20 seconds than this video was in 20 minutes.
It's too bad his explanation depends on knowing Haskell types, and programming in general. The monad idea can be used in lots of places, anywhere you can think of the problem as category theory categories.
Monad is a relationship between two data types, in this case "a" and "Maybe a", such that any functions that work on "a" will work on "Maybe a", where "Maybe" is a concrete monad. Monad laws further prescribe that performing these functions in sequence on "Maybe a" must be effectively the same as when performed on "a". We can think of "Maybe" as a kind of box, then, where the box is the "extra" stuff non directly related to the only value we want to think about - the box idea is where the stuff we don't want to think about accumulates.
Actually my description, analagous to a box, is functor, but monad is not unrelated. A monad just adds a way of changing a boxed value by applying a function returning the same kind of box. Functor, applicative, and monad are all lawful ways of creating, modifying, and combining these "boxed" values.
Alex Berg, why can't I think of a monad as a burrito? You ignorant fool.
I reserve burrito for explaining monad transformer stacks. 🙃
The unit function for burritos is obviously a tortilla
How is that any different from inheritance?
This video lacks the basic explanation of and definition of the monad. The key to a concept like this is to be able to express it succinctly and not have to elude to it via examples. I am going to state my definition or a Monad here and anyone who agrees just like the comment or comment on it.
A monad, is an evaluation that 1) allows any type of input to be entered 2)makes an evaluation as to if the data makes sense in the context at hand 3) converts the data into a context that CAN be used if possible, or if conversion to a useable data type is not possible halts the data from undergoing further evaluation by the program.
"A monad is just a monoid in the category of endofunctors. What's the problem?"
After learning Rust, this video makes so much more sense to me
This is ridiculously complex compared to what it actually is.
I assume that there are more complex cases where it simplifies things. I would have loved to learn about these.
@@aheendwhz1 buy his book:)
If you all don't like the Maybe monad, how about the List monad?
List's return is just creating a new List of 1 element (ie return x = [x])
List's flatMap (or bind operator, or >>=) is just apply a function returning a List to each element of the List and concatenate the results.
Monads are everywhere. The purpose of them is more abstract. Monads are well-established mathematical objects and because of this you can use their mathematical properties (assuming you don't use side effects). For instance, associativity.
"Monads are everywhere."
Pure idiocy. Flatjangs are everywhere because I say so.
@@vendicarkahn4860You didn't define flatjangs
The video started buffering just in time for him to say: "So, a monad is.........."
The title of the video is "What is a monad?", but it should be "Some Haskell for people who already understand Haskell and don't mind if I am a bit careless with my english while I give a Haskell example that happens to touch on just one type of monad, but don't explain what is monadic about it - oh and a plug for my book"
richtourist I don't understand Haskell, what I know about FP is some untyped lambda calculus basics, a few days of practicing in Scala and one day of practicing in Scheme to this day, but I still understand this video.
Math: Here is the definition. Let's do some examples.
Computer Science: Today's lesson is about this word. Instead of defining it, let's do something else for 40 minutes. Then let's define it at the end and see if you were paying attention.
The pen noises are not in sync with the video.
CaesarsSalad so what?
+Alfredo F. It's distracting, also I wonder why. I mean, his voice seems in sync?
You're not in sync with the video.
would you rather have the video be 3 times longer and contain 40 minutes of buddy writing stuff and not talking?
It's because the writing video is shown with the audio of the dude explaining. I agree it's kind of irritating, because it's so loud (headphones).
My favourite part of these videos is when they break out the ancient printer paper. I love the aesthetic
But where are the burritos. I demand my monads be explained in a culinary fashion.
Exaclty! You can't do proper programing without breaking huevos. The man is a charlatan, he probably doesn't even own a black tail-coat.
It would have been nice if the camera kept showing the pages during the explanation. Every time the camers flips to the speaker, one has to switch to visual memory to try keep in mind what's on paper. Thanks.
Same reaction here -- frustrating to watch as the camera keeps switching away from the material, right as you try to absorb it. Also not a great viewing angle -- hard to make out the Haskell symbols at 360p.
that's the difference between a photographer and a mere cameraman
I really didn't like the way this was explained. It was too complex for someone new to functional programming and Haskell, and it really didn't show how powerful monads can be. Another 10 minutes and a slightly more advanced example modeling a real-world problem with the Either monad would have been a lot better imo.
Where's your video? I'd like to see it please. Thanks.
True but he's not wrong, there are a lot of people who simply don't and can't understand the point of and even the meaning of monads here. We certainly could use a longer video
+Shin Kansen There's a rule in the development of anything, be it TH-cam, game dev, or writing: your audience knows what's wrong, and you know how to fix it. Maybe I'm wrong, and that longer video would have been terrible, but I know that the current way of doing it didn't quite work for me (and looking at other comments, it didn't work for a lot of others either). The best of the talks I've watched to understand monads took around 30 minutes and explained them using real-world situations (eg. database querying for an android app in Scala), and I believe that taking a few of their ideas would help, as it worked a lot better for me and many others.
could you at least link that talk then please?
He couldn't wait 10 more minutes to sell you his book.
So, we were shown an example of monad, we were told what they can be used for. But never actually explained what is it. That’s not how explanations supposed to work, aren’t they?
I'm going to give a layman's interpretation of what a monad is by describing the actual purpose of a monad instead of a specific implementation. A monad allows you to take some type, Int for example, then performs some operations/functions on it that might fail while also not producing side effects (anything that changes the state outside the function itself). So for example Java would throw an exception for 1/0, but that's a side effect and functional languages are defined by the absence of side effects as much as possible. Java Optional is an example of this kind of pattern: don't fail, propagate the error to the caller.
Another component is that Monads allow you to mix functions that take Int with Optional without doing Optional everywhere on everything, which would be verbose and ugly. If you have to deal with sync/async functions interacting you know the pain of this type. So there's multiple levels of producing no side effects at play here: program runtime and the structure of code itself.
tl;dr Monads allow error handling in a no side-effect way by propagating errors up to the caller while also allowing you to use other functions that don't require error handling (think Int vs Optional in java).
An extremely long prelude which assumes a lot of knowledge and introduces lots of unexplained items so that one is led out into the quicksand and left to sink in a sea of new questions. One's fear of monads and the impossibility of understanding them increases.
> impossibility increases
this videos has become much more comprehensible after learning about rust’s implementation of ‘enums’ and ‘match’ blocks
yep, rust's results and options are monads (and the ? operator is basically do notation)
Worth noting that the Maybe monad is a core concept in Rust as well, except it's called Option, and Just/Nothing are Some/None respectively. Other monadic types can be implemented with traits.
WHAT????
Why have I been looking through monads for so long then
While I've used option many times in rust
Rule of thumb is: if your instructor can't explain it in simple layman terms, he doesn't understand the consept himself
Sadly, there is genuine irreducible complexity in the world, and some things cannot be explained simply.
"So Monads are a concept that was invented in mathematics in the 1960s" And here I thought Leibniz was from the 18th century.
This was a bad video about monads because the guest professor only speaks in terms of Haskell the entire time and never gives a conceptual overlook on what monads actually are.
That besides the fact that he keeps talking about concepts he never properly introduced and other smaller problems.
There isn't one thing Monads are, outside of the "bind" (or "join") and "return" (or "pure") operators. Monads are things that support those operations.
And there are a LOT of things that are monads. Lists are monads, for example (they model non-determinism). Continuations and callbacks are monads (it's called Cont). Functions themselves are in fact monads.
It's kinda hard to stress how fundamental they are to folks.
Romário Rios Also, it's a bad video about Monads because after he spends twenty minutes talking about Haskell he does a "buy my book about Haskell" promotion. Seriously that's the kind of naked capitalism I'd expect from a late night infomercial, not a -phile video.
Monad - is glue to compose functions. That's it.
The Applied Category Theorist in me wants to be angry, but instead I am now resolute on playing this video in front of this weekend's Applied Category Theory #3 conference at UC Riverside to prompt discussion!
"I want to explain this obscure idea, so I'm going to use the most obscure commonplace language I can and never actually say 'this is the thing'".
The hell's a monad?
GTG3000 i thought he explained it pretty well, if you didn’t understand this maybe you should start learning about some of the basics of functional programming before learning about these kinds of things?
@@aNotoriousPhD Yes, learn what a monad is, and then watch the video again.
The video was easy to follow, and I think I understood the concept of a *Maybe monad*. The problem is that I've no Idea how to apply monads to wildly different effects. The video should have had examples of those also.
In functional programming, a monad is a mechanism that allows programs written in an otherwise pure functional language to perform impure operations that aren't allowed in the functional paradigm. Each pattern of impure operations has its own specific monad. For example, Professor Hutton's video describes the Maybe monad, which deals with situations where the value may not even exist. The IO monad deals with data that's either inputted from or outputted to a physical device (I/O), and there are other monads that are used for other purposes.
In Haskell, monads are implemented as data types. They're called "abstract" data types because their contents can be of any type. The value x in a monad with constructor M is written as "M x". The constructor creates a monad value, i.e. a value inside the monad. The monad acts as a sort of tag or label that keeps the value separated from the functionally pure parts of the program. Internet tutorials variously call it a "spacesuit", "toxic waste dumpster", and other colorful metaphors that imply containment or isolation.
Each monad has a function, usually called "bind", that implements the special handling associated with the monad. In Haskell, bind is represented by the operator ">>=". The first argument of bind is a monad value, and the second argument is a function that takes a raw value (not in the monad), tries to calculate something, and then returns its results wrapped back up in the monad again. Bind does whatever impure things it's programmed to do, which may or may not involve the first argument, and then it may or may not extract the value from inside the monad and pass it to the function, depending on whatever the rules for the monad are.
In pure functional code, operations can be chained together through function composition, as in y = h(g(f(x))). With monads, bind replaces function application: yM = fM(x) >>= gM >>= hM, where yM is a monad value and fM, gM, and hM are functions that take regular values and return monad values. The impure processing of the monad is handled automagically, and you can use Haskell's "do" notation to make your code even more compact. 🙂
"It's just a monoid in the category of endofunctors" - well, don't laugh at it and try to decode what a monoid, functor, and endofunctor really mean. Functor - is a morphism(i.e. transition, transformation) from one category to another. Endofunctor - morphism from one category to the _same_ category. Monoid consists of following components: 1. A set of objects from a category. 2. A _transitive_ binary operation that can be applied to the objects in the set (like addition for integers). 3. Identity object, that is when used with any other object in a set using given binary operation returns that object. So, a monoid would be a set of all non-negative integers and addition for binary operator with identity element 0. Or set of all positive integers and multiplication operator with identity element being 1. Note, that division or subtraction cannot be used in a monoid, as they are non-transitive.
‘nothing, which is a constructor of the maybe type’ this sounds hilarious i love it
If you understand this video you probably already know enough about monads that you don’t need to watch the video.
I am none the wiser.
Paul Bates Why? I thought it was a decent explanation.
Joshua Barretto it's not very beginner friendly tho, it is accurate, but unhelpful for someone uninitiated.
I recommend Brian Beckman's video on the subject.
Think of monads as pipes in your bash, e.g. echo 1 | program1 | program2. Echo puts stuff into the shell context so you can use it to pipe it (return) and the | is just the >>= operator.
Tl;Dr: you use this stuff for sequencing things and you wrap it in a type to do the extra behavior in between (e.g. wait for async things, stop on error).
Joshua Barretto, Did you know what a monad was before you saw this video?
There are many ways to skin a cat. Graham decided to use an example which is simple enough that you can explain all the details without expecting too much background. This is maybe not so convincing in terms of usefulness but if you are using a real world example you will wave your hands how it is actually done.
I listen to this sometimes cause I have sleeping problems. Never fails
As someone who comes from Python and Java, this makes no damn sense XD
@@fennecbesixdouze1794 So much self-reflection. I pity you
@@fennecbesixdouze1794 I think you need therapy, buddy
I come from the Python world too, and took up Haskell thinking it was just another language. It's not. It's loaded with concepts, and new ways of thinking. Definitely something to look into if you're growth oriented, and your Python code will probably improve vastly too... such is the promise, and I've seen a little of that improvement in my own Python code.
@@fennecbesixdouze1794 Perfect example of how toxic the Haskell community can be.
This the perfect example of scientists naming a simple concept in the most abstract and obscure way possible.
"Monads are a concept that formed originally in the 1960s"
*Leibniz rolls in his grave*
We are not talking about that kind of monad. Completely different concept with the same name.
I know you probably know that, I'm just saying it for people who don't know.
There something called monad in philosophy. Here we are talking about monad from category theory.
@@Alkis05 Yeah... however, beyond the name, the conceptualization itself remarkably similar. Remember, Leibniz is the one who invented Calculus (I know about the controversy and I just feel like edging it on), and we use more of Leibniz's notation in modern Calculus.
@@Garland41 What calculus has to do with anything? Completely different area of mathematics. lol.
Category theory had an independent origin and the concept of monads there grows organically from other entities. It has very little in common with the philosophical concept.
As Category theory itself would put it, the characteristics of the concept itself is less important than how it connects and relates to other concepts. And those relations are very different for the two monads.
I learned about Lebnizian metaphysics before touching any computer science, so for me monad as an entity that is independent substance yet in divine coordination with other monads was a natural concept for me. The computer science one is confusing as heck. Why did they use the same word???
Both can help define two answers from no answer by capturing patterns
If you weren't scared of monads before, you are now! Professor Graham Hutton just made sure of it.
By the way, my browser's spell check doesn't know monads either. It suggests gonads or nomads!
A more specific criticism of this video:
You lay out a bunch of concepts that are relevant to monads, but you don't (or if you did, I missed it) circle back and *define* monads *in terms of* these concepts... so I might fully understand the concepts, but I still can't pinpoint the answer to "what is a monad?". It's like if you asked "what is addition?", and then go on to talk about collection of items, and combining items to create bigger collections, and.... fail to say that "addition" is "the act of combining" according to those principles.
So, I humbly request a follow-up, that both says more specifically what aspects of all of this actually define what a monad is, and also maybe goes into more examples and/or depth in various ways.
he literally does exactly what you're asking around 16:05
@@thoperSought I disagree. Where’s the definition there?!? If you’d said 16:44, that would have been closer, but it still falls short to me.
@@DavidLindes
I'm not sure of the exact time stamp, but the point is that the definition of a monad is that it's the combination of the three things he's explaining *_around_* 16:05
@@thoperSought I stand by my original statement. The pieces have been explained, but the word has not been defined. And as for your attempt at a definition, too much of “the three things he’s explaining around 16:05” are specific to the Maybe monad, so that doesn’t help me understand what a monad _in general_ actually is, really. Thankfully, Wikipedia did _slightly_ better, and I have some idea now. That doesn’t invalidate the critique of the video content, however. (Which I rewatched all of, and still didn’t catch a definition.)
@@DavidLindes
so, I def. see where you're coming from-I didn't get it when I originally watched this video, either.
otoh, you asked for him to _"circle back and _*_define_*_ monads in terms of these concepts,"_ which I argue that he did. you're right that he did it at 16:44. he laid out the three components Maybe, and then said, _"A monad is some kind of type constructor, ..., together with two functions that have these two types here."_
I would argue that it's not sufficient-that _no_ definition _can_ be sufficient-unless *_you_* have enough background in specific cases to see what the monad factors out.
I watched a talk once where the speaker compared some code using fold/reduce with a few similar for loops, and showed how fold was factoring the looping out of the code. map (which you may know can be defined in terms of fold) does the same thing.
a monad factors *_something else_* out of code in *_the same way_* that fold factors out the looping.
one of the things that makes this really difficult is that the "something else" with monads is harder to pinpoint, and a lot more stuff fits into that slot.
a great example of taking a simple problem and making the solution as complicated as possible. 40 years ago I learned a simple rule divide nothing multiply everything. Surprisingly I dont get division by zero errors.
I like how he just says "We're going to create an expression that can be either a value or a division" and never really makes it clear why we're ONLY doing division here. You realize, halfway through the video, that it's in order to highlight for the "divide by zero" case, but by that point you've been scratching your head for several minutes wondering why division is the only operation we're dealing with.
If he'd said at the start "We're going to create a class that can represent mathematical expressions, so it has Value, Add, Subtract, etc etc etc…" AND THEN focused on the division case I feel like that would've helped remove a lot of confusion.
Also I still don't really get it tbh. He goes on to say "oh there are a few different types of monads" but I feel like it's critical to know what those monads ARE -- this video just makes it look like glorified error checking.
He doesn't really emphasize it in the video, but the heart and soul of every monad is its bind function (>>=). A monad is any data type that has a bind operator. bind is what implements the defining effects of the monad. Instead of chaining operations with composition, as in y = g(f(x)), you chain impure operations with bind: yM = (M x) >>= h >>= j.
After watching this video, I'm left with one question: "But seriously though, what is a Monad?"
Definition around 16:40 which you can skip to if you already understand Haskell (or OCaml) type annotations.
Basically in the Maybe monad, its a constructor (like Maybe) and two functions:
"return" which takes a value of type a and returns a new value passed through the constructor (so in this case type/value "a" becomes "Maybe a") and the function (or monadic sequencing operator) which looks like ">>=" that basically allows you to chain operations (that may fail) so it takes a type (Maybe a) and a function which goes from (a to Maybe b) and (finally) returns the Maybe b
Thanks for help saving a lot of time and actually giving an understandable explanation. All the preface was utterly unnecessary imo and I dont even write FP!
@@Ytuserqf Really glad that I could help, reading the comment I wrote again, I think I was smarter then! That makes me a little sad, lol I am getting dumber I guess.
These videos serve more to pique my curiosity to go learn more rather than actually explain the concepts fully. In that regard, kudos!
This is awesome if you're trying to learn Haskell, as I am. Great video :)
I agree about the use of the math terms (not so much as he argued for it) because as soon as you need to look up the properties, extensions, implications, etc. of "effects" you're immediately going to run into the math terms anyway. Alternatively you can come up with a whole language that's not as "scary" and meticulously rewrite all of category theory, type theory, and so on, but that's adding complexity, not removing it. "Polymorphism" is one of those "scary" terms but nobody bats an eye, even though it's a morphism just like endomorphisms, isomorphisms, and loads of other gifts from category theory.
Edit: I DEEPLY regret reading the comments below.
I totally get needing to return Nothing rather than actually dividing by zero. Preempting errors is better (and faster). I do it in my code all the time.
So I understand having to create a new safeDiv function that would simply not attempt the division if the second variable was 0. I get passing the values on to another function conditionally.
I even get the idea of no longer just returning an integer, but also returning another type that indicates whether the division took place or not. I even get putting those together in a single object, so you have a single output.
But then he puts it back into the program, and still has to do a bunch of checks again. And I am completely lost. What's the point of that single object if you still have to check for it?
And when he talks about how the program is simpler, it's not. It still contains multiple checks. One check, to test for Nothing and fail makes sense. But two? How does this help? You just jumped straight to nested concepts (which I didn't even realize were nested until the comments told me they were).
I still don't know what part of any of this was the monad, whether it's a part I understood or a part I didn't.
I also don't know what binding does. Does it just mean sending the variables to another function? Is it just having a function callback?
I am left with more questions than answers, I think.
Bindng is really the core magic of Monads, and why we have to define each one uniquely. Let's pretend you have some Context that has a type slot. You've seen Maybe a = Just a | Nothing. But let's ignore the specific context for now. What binding does is take a value with Context, and a function that takes a value and returns a new Context value, and then systematically plumbs that context all the way through.
Let's get concrete to help show what that means.
Imagine a monad with NO context, "Identity." Identity a = Identity a. Pretty useless except for specialist purposes. But consider it for a second.
What does something like this program "do": (Identity 5) >>= \x -> return x + 1
It makes an Identity 6. Now, Identity has 0 context at all, right? So it's really easy. All the bind operator does is pattern match out the number and pass it forwards to the new function.
But now think about it, what happens if we used Maybe. We've got 2 cases:
(Just 5) >>= \x -> return x + 1
(Nothing) >>= \x -> return x + 1
For the first case, the bind operator's function says, "Oh I have a value. I'll pass that along to the function, and then return what it returns." This is exactly like what the Identity monad did, right?
The second case though, the bind operator looks and sees it has a Nothing. "Well dang, I can't even CALL that next function, I have nothing to give it at all. Literally the only thing I could possibly do that would typecheck is return Nothing. I have no other options."
I hope this helps explain what binding is and how the program "knows" not to do the extra work of calling forward.
Monads are very powerful because they actually model programs that build programs, at runtime. This is fundamentally more awesome than if statements. Let me show you one final (simplified) example. Let's imagine we have an imaginary function httpGet. Its type is Url -> Maybe String (please note, this is not the real world type we'd use and we could never use it, but bear with me for a moment I'm explaining something bigger here).
When you need to do 2 of these in one function and use their values, Maybe suddenly makes our life incredibly easy.
fetchUserDetails :: String -> Maybe UserRecord
fetchUserProfile userName = do
userDetails
The reason that this monadic approach is nice is that it abstracts the "checking" away. The failure "propagates" if it occurs.
I'd also recommend Scott Wlaschin's talks and blogs on "railway-oriented programming." This is the best explanation of this that I've encountered.
@@KirinDave Hi there! I know it's been over a year since you posted this comment, but I'd like to thank you regardless. This is honestly the best explanation for monads I've ever heard. I've been struggling with the concept for a while and I finally get how straightforward it is now. Thanks!
@@gogogalian I'm proud I could help you.
So “maybe monad” is basically for “managing unwanted effects” of side effects while making them
And it is a partial function which has recursion in its definition as I understand
Can you generalize/define monad’s general purpose by intoducing purpose and definition of other types of nomads by examples
After 20 minutes, I came to know that he is the author of the textbook we are taught Haskell from, at the University
Same. Universities are a scam to keep these terrible languages and books going.
AugustusPugin I don't think Haskell is a terrible programming language. It is really interesting. Functional programming shows you a different way to think about programming
+AugustusPugin you mean Java and PHP? Then yes, I totally agree.
Watching these videos to prepare for my uni course in functional programming, your book is our curriculum, very fun to be introduced to the topic by the author himself :D
Monads are insanely useful and not THAT unusual. I'm a scala dev, there are a few of us. Many other langs with monadic things in them too. Also, if you think this video didn't make sense or you got impatient you are missing the point. The monad concept is simple but simple is not the same as easy. Have to take a simple example to unpack the concept. In addition, you will only really understand this by playing around with them. Same with all programming really. Seriously it's worth understanding if your language supports this sort of thing. Your code will become simpler and doing things like dealing with exceptions and acceding the db for example becomes an order of magnitude simpler to manage,read and reason about. Don't miss out.
what I understand is that a monad is like a wrapper for a value that could no be there, at least the Maybe monad that is used as example, like a Promise in javascript. So instead of getting the value or an error, instead you get a thing that gives you the value if the operation worked, and nothing if the operation went wrong (instead of thowing an error at you)
Don't worry, at 16:57 the "What's the point of all of this?" comes
The issue is that if I am anything to go by, people went to the comments to ask what any of this means after finishing.
I was at the book recommendation when I scrolled down to see if anyone had an explanation, but I didn't find one. The video is just incredibly bad at teaching anything to someone like me, whether that is because I don't know Haskell or because I don't know what a Monad is in mathematics or whatever else, I don't know.
you mean 19:27
@@FKInMyCoffee lool
A monad is something that everyone loves to understand but nobody can explain how it is useful.
RIP Amazon forest 2017
This is the first accessible explanation of monads I could find. I already knew C# Tasks and JavaScript Promises were similar to monads, and the same for F# Options, but this makes it all clear.
This became understandable to me only after watching the monad video by “Studying with Alex”
Highly recommended for programmers from OOP land
@@vikingthedude thank you!!! I'll check that channel out!!
Sounds like a high falutin description of an if function.
I'm thinking only professors need to understand jargon coined by professors. For commoners like myself, I'd prefer keeping it simple.