The Absolute Best Intro to Monads For Software Engineers

  Рет қаралды 680,259

Studying With Alex

Studying With Alex

Күн бұрын

Пікірлер: 903
@asadsalehumar1011
@asadsalehumar1011 3 жыл бұрын
Hands down the most awesome explanation of Monads on KZbin
@neogen23
@neogen23 2 жыл бұрын
My experience as well, though I realise as much having already understood the concept via classic methods (see a book on Haskell), so I was like "Yep, that's totally it". I doubt it would have helped me if I had used it as tutorial material. Still, a stellar explanation
@AutoFirePad
@AutoFirePad 2 жыл бұрын
It turns out that we have been using monads without even knowing it for years.XD
@erikkostic8271
@erikkostic8271 Жыл бұрын
Feel you
@stopper0203
@stopper0203 Жыл бұрын
Agree
@quantisedspace7047
@quantisedspace7047 Жыл бұрын
Maybe it was. I gave up when I heard the stupid music.
@gargshishir3
@gargshishir3 2 жыл бұрын
After maybe 10 years of periodically going back to the definition of monads, googling and still not understanding what the hell they are, you have done it! Thank you, one less mystery in life.
@KingTheRat
@KingTheRat Жыл бұрын
I watched this video last year, and this year, I already do not remember what it is. Time to watch this video again. :)
@gargshishir3
@gargshishir3 Жыл бұрын
@@KingTheRat I did that recently too 😆
@RickGladwin
@RickGladwin 7 ай бұрын
Yeah I saw the thumbnail on my feed and was like “ah, it’s that time of year again - time to learn what a monad is” 😅
@vh5x7
@vh5x7 12 күн бұрын
@@KingTheRat ahhahahahah
@nobodyinparticular8219
@nobodyinparticular8219 2 жыл бұрын
Very good explanation, finally someone who's using a programming language which people who don't yet know what monads are can actually understand. Another good video on the subject is Brian Beckman's "Don't fear the Monad" which explains it in a more abstract way, but still using familiar terms. Other videos, and especially Computerphile's video were completely inaccessible to me and left me thinking that I'd need to spend months studying category theory or at least read a book on Haskell before I could understand this concept. You and Brian made me realize that I had actually invented monads on my own and have been using them without knowing what they are.
@evanroderick91
@evanroderick91 2 жыл бұрын
I'm not familiar with this programming language. What language is this?
@rakandhiyaaa92
@rakandhiyaaa92 2 жыл бұрын
@@evanroderick91 I think this is typescript
@younes3573
@younes3573 2 жыл бұрын
@@evanroderick91 as mentioned before it is TypeScript: JavaScript but with types
@denisg1208
@denisg1208 2 жыл бұрын
I agree with you about video ‚Dont fear the monad’. Also explains it really well
@MrRedstonefreedom
@MrRedstonefreedom Жыл бұрын
It's funny you mentioned the computerphile video because I likewise, even in using monads wherever applicable, watched that video and felt like I understood it even less. Even funnier still is the disclaimer he gave of "well people criticize mathematicians for not being able to explain their concepts in relatable terms, but I think they should just get over it". And it's like... they will get over it, by just ignoring their work & having to rediscover it anyways in their own contexts.
@scheimong
@scheimong 2 жыл бұрын
That was fun to watch. I've been writing rust for a good while now, so basically I've been using monads everyday all this time without knowing the concept's technical name. Watching you refactor bad typescript step by step into rust felt funny.
@ChrisD__
@ChrisD__ 2 жыл бұрын
And this explains why don't understand Rust... I didn't understand monads!
@JordanManfrey
@JordanManfrey 3 ай бұрын
One helpful trick that can help people adopt/be aware of a defined technique or pattern is to avoid giving it a name that sounds like a portmanteau of “moron” and “gonads”
@Microphunktv-jb3kj
@Microphunktv-jb3kj 3 ай бұрын
@@ChrisD__ u cant understand rust, because rust is a political marxist cult of mentally ill activists good luck in ur cult journey : ))) rust is literally trojan horse in linux kernel
@valley-artifact
@valley-artifact Ай бұрын
Options in rust aren't monads, they're just a normal wrapper type you destructure manually, there's no "run" function
@dcuccia
@dcuccia Жыл бұрын
I mean, "Its just a monoid in the category of endofunctors. What's the problem?" Scott Wlaschin also does a great job of explaining monads graphically with his "Railway Oriented Programming" talks. But this was a great "part to whole" way to take a single use case and expand the concepts, step by step. Nicely done!
@MatthijsvanDuin
@MatthijsvanDuin Ай бұрын
Or, perhaps more clearly phrased: a monad is a single-object category enriched over the category of endofunctors ;-)
@JoshuaKisb
@JoshuaKisb 2 жыл бұрын
first video that actually explains monads in sensible approachable way. thank u very much
@Lambda_Ovine
@Lambda_Ovine 2 жыл бұрын
Oh, so this is what they mean when they say that monads can be used to avoid side effects but can replicate the effect when you need to. Say for example, Instead of having a global array that is referenced and mutated by every function to concatenate logs into it, you can return a concatenated array as part of a monadic value, one that is created at the beginning of the chain and is returned as a value at every step of the way 'till the end. I mean, in this case we are using an array object, so it's probably still being referenced as a pointer, but still, the concept stands as it belongs to the chain of operations alone.
@julestburt
@julestburt Жыл бұрын
I founded Vancouver's Functional Meetup which ran for 3 years...and we discussed monads a lot!! I had a lot of ongoing questions. I saw many presentations, yet I was always left wondering / wishing someone could actually show me a 'monad' rather than discussing the apparent philosophy or upper purpose! Finally, someone explained it with great code examples, which I could easily relate to Swift (my language) and completely and finally understand monads...I had assumed one didn't really need to know 'monads' to use them, and it turns out with arrays, maps/flatmaps, optionals, and even a plug in Then promise library - all these were monads of course and I didn't need to know one to use one...but your explanation nails it! Many thanks!!
@papetoast
@papetoast 2 жыл бұрын
As someone who didn't know monads, this is an excellent video! You started with an iterative approach on simple examples to give an intuition of why the idea of monads is useful. Then after having the intuition you give a more abstract, rigorous definition, along with real usages. I think I wouldnt have been able to understand the abstraction as easily if there wasnt the simple examples in the beginning. Then you give a summary to help remember the content of this video. Overall I think the flow is great and the pace is just right. Sometimes I have to pause a bit to understand the code but I never have to think really hard to understand since the leaps in logic are always small enough. Thank you for making this video!
@CFEF44AB1399978B0011
@CFEF44AB1399978B0011 Жыл бұрын
I'm blind and you were able to describe your content without using this and that while pointing at places in the code. nice work.
@steveloco1170
@steveloco1170 Жыл бұрын
bro WDYM YOU ARE BLIND AND WATCHING KZbin
@CFEF44AB1399978B0011
@CFEF44AB1399978B0011 Жыл бұрын
@@steveloco1170 you do realize blind people live normal lives?
@jhoughjr1
@jhoughjr1 Жыл бұрын
@@steveloco1170 main thing to know is "blind" is shorthand for visually impaired. Also you can learn from hearing too.
@NOT_A_ROBOT
@NOT_A_ROBOT 7 ай бұрын
​@@steveloco1170 not all blind people are completely blind. some at least have partial vision
@jcolt452
@jcolt452 2 жыл бұрын
How on earth did you break the curse!? .... "Once you understand Monads you lose the ability to explain them"! 🤣
@aiocafea
@aiocafea 2 жыл бұрын
you have to trick a veteran functional programmer into helping you if you start explaining monads to enough people that already understand them, eventually one will tell you 'oh you don't _actually really_ understand monads unless you understand…' and suddenly you will feel this clearness in your brain you can suddenly explain this concept and all of the useful ramifications
@Bergerons_Review
@Bergerons_Review 2 жыл бұрын
I think that's true for most coding problems ;)
@GesteromTV
@GesteromTV Жыл бұрын
This is greate video that explain how to use monads and how fo recognize them, but in true math style there is whole universe that you skiped.
@ArturCzajka
@ArturCzajka Жыл бұрын
@@GesteromTVAnd that's how he shoved it into a 15-minute video, and not a 60-minute lecture 😝
@Lee-qj4hk
@Lee-qj4hk Жыл бұрын
Monads are a brain virus which makes you believe in Monads
@youngcitybandit
@youngcitybandit Жыл бұрын
This seems like a very intuitive pattern but at the same time I never knew this could be so formalized. Thank you I learned a lot
@connorkapooh2002
@connorkapooh2002 2 жыл бұрын
Dude. This was fucking sick, please keep producing videos like this. I think there's also a lack of beautiful visualisations for more advanced concepts (which makes sense because more people are going to be beginners). Keep it up man, your animations are absolutely gorgeous :)
@MrRedstonefreedom
@MrRedstonefreedom Жыл бұрын
Jesus, this is such a robust explanation. This could be watched every 3 months just to reconsider newly-encountered applicability. I already came to the same conclusions about monads in programming (as a design pattern, in any kind of paradigm or language), and done a lot of deep thinking, but even still, this is such a wildly useful video as a consolidation tool. You've given a lot of excellent visualizations that make aspects-management & its expression a lot easier.
@erikgrundy
@erikgrundy 2 жыл бұрын
I've always thought that the definitions people used are always more complex than they need to be. I'm glad you've managed to explain it in a way that feels like something a programmer would do
@AndreiGeorgescu-j9p
@AndreiGeorgescu-j9p 10 ай бұрын
By programmer you mean code 🐒
@erikgrundy
@erikgrundy 10 ай бұрын
@@AndreiGeorgescu-j9p i don't, and i'm a little confused at what you're implying. do you mean that no "real" programmer requires it to be explained like this? or that you don't think the code in the video is very good? please, enlighten me
@AndreiGeorgescu-j9p
@AndreiGeorgescu-j9p 10 ай бұрын
@@erikgrundy a software engineer is supposed to be an engineer. An engineer uses math and science to solve real life problems. However "software engineers" are the only kind of engineers who hate math and science and think even simple basic math is "too complex" and are always looking for immediate answers on "how" to use something, with very little understanding of "what" something is or "why" it is. The explanation above is terrible for very many reasons but mainly because he doesn't actually explain anything any what a monad actually is, it's just overly convoluted examples of what you can do with it which ironically is more complex than if somebody just explained what it is. You saying "feels like something a programmer would do" means code monkey because actual software engineers understand math and don't explain things this way
@mike10240
@mike10240 8 ай бұрын
​@@AndreiGeorgescu-j9ppretty elitist take in my opinion. I think the video does a great job at highlighting the use and benefits of monads from a practical perspective. Many people, engineers and otherwise, benefit from illustrative examples as points to jump off of and then abstract. You are free to complain about what you think engineers should and shouldn't do until the cows come home, I'm sure that's much more useful. Or, if you're so concerned about software pedagogy, why not put your money where your mouth is and make a guide yourself? But I understand, hiding behind cheap talk is much easier. These lazy software engineers, right?
@bigpest
@bigpest 7 ай бұрын
⁠​⁠@@AndreiGeorgescu-j9p in the same breath, “engineers solve real life problems” and “they only care about *how* to use tools” Using tools is what solves problems. It makes sense that engineers prioritise practical use over formal understanding. Save the high-level math for academia and research.
@anangelsdiaries
@anangelsdiaries Жыл бұрын
The fact I listened to that and connected on my own that futures might be a type of monad as well makes me somewhat proud.
@denys-p
@denys-p 2 жыл бұрын
Just for reference, in C# flatMap for lists (actually, all collections that provide IEnumerble interface) is SelectMany in Linq. Future/Promise is the Task. One more interesting thing - async/await (combined with Task) is very close by it’s behavior and purpose to IO monad (not mentioned here) - it “infects” function so you need to make functions that call it async (or, at least, return Task) as well. And it brings a big mindset shift, starts building understanding that we want to keep “IO monad” part as small as possible, splitting logic and IO. It will allow to write most of tests without mocks at all. And the rest that works with “outer world” (db, user input, other services calls etc) better to test with real interaction, e.g. integration tests.
@MrRedstonefreedom
@MrRedstonefreedom Жыл бұрын
The second part you wrote is potentially a good point, but I'm not convinced it's true. I know exactly what you mean by "infection" (I call it "prionic", and if someone doesn't know what a prion is, I go for ice-9 if they've ever read Vonnegut). But, I'm not sure it's really possible to have async in any kind of way where it doesn't "infect" all of its uppers. Actually, callbacks in JS would possibly do this. But that's more a matter of using global state. Although, additionally, mutex's in general work this way. Thinking of reentrance patterns and such. Ok, you've convinced me. Yea I think this is a unique quality for Task. Even deeper, I think this may be a unique quality for Monads, overall. An accessory requirement for that to be the case is BTW this is somewhat similar to the mathematical concept of "absorbing elements". I think Undefined, though, would most-closely mimic the concept of a synthetic (ie intentional union with) construction of a category with an absorbing element.
@MrRedstonefreedom
@MrRedstonefreedom Жыл бұрын
**An accessory requirement for that to be the case MIGHT be that it's a typed language. Though I think that's just a straight matter of "in order to be less immediately annoyed of categorically wrong implementations"
@KaiHenningsen
@KaiHenningsen Жыл бұрын
@@MrRedstonefreedom Typescript (in the video) gets compiled into normal Javascript, mostly by stripping away the types. So the async/Promise stuff usually becomes the exact same operations in Javascript. For that matter, the node.js runtime has a utility function util.promisify() that converts a callback-using function into a Promise-using functions, and Promises have .then, .catch, .finally etc that resolve Promises with callbacks. The two are essentially equivalent.
@Cool-Game-Dev
@Cool-Game-Dev Жыл бұрын
A fellow c# bro.
@TheGarretThief
@TheGarretThief 3 ай бұрын
Dude, I literally was using Optional without knowing what is it and how it actually supposed to be used. Huge thanks for explanation, found your channel today and already fallen in love with this and passwords videos!
@chachan4142
@chachan4142 2 жыл бұрын
Thank you. this video is very practical, informative, and truly demonstrates what can be achieved with monad with actual example and not just the abstract concepts of it all. Best one yet that I've seen on KZbin. You've earned a new. subscriber!
@AllAnglesMath
@AllAnglesMath 21 күн бұрын
This is easily the best explanation of monads I have ever seen. Especially the diagram at 10:40 made everything click for me. Thank you!
@arongil
@arongil 2 жыл бұрын
+1, this video taught me exactly what monads are from a practical standpoint. Thank you!
@_blank_3677
@_blank_3677 2 жыл бұрын
Dude… years… years I tell you!!!! Why does everyone else suck sooooo bad at explaining this! Finally! I feel complete. Ty
@ZackFreedman
@ZackFreedman 2 жыл бұрын
Great explanation. I'm going to use this as a benchmark when I do actual education videos.
@crckrbrrs
@crckrbrrs Жыл бұрын
yeah, now that i think about it the oscilloscope video was quite similar to this one
@d0m186
@d0m186 8 ай бұрын
Best video i have seen on this topic. Most videos start with explaining monads, monoids, and endofunctors and are completely overcomplicated. Starting with an easy to grasp example is way better
@buscape-22
@buscape-22 2 жыл бұрын
By far the most amazing explanation i've ever read. Nice examples, made the concept a lot easier to understand!
@GregoryMcCarthy123
@GregoryMcCarthy123 3 ай бұрын
This is my favorite explanation of Monads. Never saw such a simple yet concise explanation!
@dawid_dahl
@dawid_dahl Жыл бұрын
One thing I’ve noticed that is tricky is when you have a value wrapped in several monads. For example, if you have a value that is asynchronous and also can fail with an error. Then you have a value wrapped in a Future/Promise/Task as well as an Either. Would love a video about how to deal with this complexity. How to traverse between different monad lands.
@Holobrine
@Holobrine Жыл бұрын
You’d probably pass one “runWithLogs()” into another, nesting the functions in the same way the types are nested
@ivanjermakov
@ivanjermakov Жыл бұрын
Yep, because Promise.then() has the same type signature and meaning as flatMap (or bind in monad). It transforms promise, using a function transforming wrapped value into a new promise.
@HolyAvgr
@HolyAvgr Жыл бұрын
​@@ivanjermakov wouldn't this be trivially solved by back-tracking the function through the unwrap, since both monads are Generic in their implementation? If you have a Future, what you probably have is something in the form of future(optional(5)), which can also be expressed as a chain operation as: let result: Promise = createOptional(5) | .createFuture($0) in which case you should probably be able to do something like `result.value.value` which should resolve without much problem: Unfulfilled promise would nil .none in the optional would also nil
@ArturCzajka
@ArturCzajka Жыл бұрын
Keywords are: monad transformers (more popular, safer to start with this) and extensible-effects (imho cooler) 😄
@genericperson3122
@genericperson3122 5 ай бұрын
I've been trying to understand monads for literally years and this explanation is what made it click.
@CARDCZARMAFIA
@CARDCZARMAFIA 3 жыл бұрын
I loved this video. Would love to see some explanations on applicatives and functors as well and some fp-ts examples. The pipe and flow makes using monads and functors so nice
@JamesWalker-rs1ps
@JamesWalker-rs1ps 2 жыл бұрын
Hey, this is great! You've got a good way of explaining things using plain English and building concepts from a basic level.
@CartoType
@CartoType 2 жыл бұрын
Very interesting and new to me. One small thing; what you call a caret, < or >, is more properly known as an angle bracket when it is used as a delimiter. This is a caret: ^.
@NicholasShanks
@NicholasShanks 2 жыл бұрын
Yes, worst part(s) of the video, that.
@jasonzuvela
@jasonzuvela 2 жыл бұрын
Exactly! So painful to hear every time. en.m.wikipedia.org/wiki/List_of_typographical_symbols_and_punctuation_marks
@31redorange08
@31redorange08 2 жыл бұрын
That's a circumflex.
@0LoneTech
@0LoneTech 5 ай бұрын
This is a caret: ‸
@atanugayen3030
@atanugayen3030 Жыл бұрын
I kept seeing this video recommended to me, but I avoided it everytime thinking "this is gonna be too complicated, I'll watch it later when I have the time/energy." Glad I finally bit the bullet and watched it... was not disappointed. Fantastic explanation... please keep making videos like this!
@Daniel_WR_Hart
@Daniel_WR_Hart 2 жыл бұрын
I watched a bunch of talks about what monads were, but this was the first to make me realize that I actually wrote one unintentionally last year while trying to learn about design patterns
@therealguanzo
@therealguanzo 2 жыл бұрын
One of the best videos on programming I've ever seen. Subscribed. Please make more!
@kebien6020
@kebien6020 Жыл бұрын
"A monad is just a monoid in the category of endofunctors, what's the problem?" for anyone wondering, was satire from the beginning (though the first part was taken from a math book, where the sentence does make sense in context).
@MatthijsvanDuin
@MatthijsvanDuin Ай бұрын
Categories for the Working Mathematician, and yes that iirc it's just given as an example of monoid objects after monads had already been discussed
@kellybmackenzie
@kellybmackenzie Жыл бұрын
4:43 Thank you SO MUCH, seriously! When you said that it instantly clicked. This genuinely helped me so much, thank you!
@OroborOSX11
@OroborOSX11 2 жыл бұрын
The fact that Swift has built in operator support for optionals using ? is so nice. It’s nice to be able to wrap up this behavior into a simple type declaration like User? (equivalent to Optional).
@yahyaadinugraha1058
@yahyaadinugraha1058 Жыл бұрын
dart as well
@AndreiGeorgescu-j9p
@AndreiGeorgescu-j9p 10 ай бұрын
It's not equivalent
@MadaxeMunkeee
@MadaxeMunkeee 2 жыл бұрын
This video is a true triumph. Thanks so much for making it!
@vikingthedude
@vikingthedude 2 жыл бұрын
This is some good stuff. I'm also glad to see you have other videos. Hoping you get more subscribers, you deserve it
@codeman99-dev
@codeman99-dev Жыл бұрын
Very nice overview. One thing that could be helpful: flip the "normal" and "monad" land in your state graph (9:45) and then explain that "wrap" is sometimes called "lift".
@wcarmon7
@wcarmon7 2 жыл бұрын
You have quite a gift for education. Thanks for taking time to explain this.
@ivanjermakov
@ivanjermakov Жыл бұрын
13:30 It's called flatMap not only for lists, but for any type that introduces structure. More generally, it's called bind or concatMap, it has a type signature of (struct: Struct, transform: (value: T) => Struct) => Struct, and means "Map a function over structure and concatenate the resulting structures". It is possible, because any monad must also be a monoid: define how to combine structures. Basically, monad is a very general interface for flatMap.
@jongeduard
@jongeduard Жыл бұрын
Thank you for this extensive explanation! 👍It's really useful as a background knowledge behind a ton of things in Rust that I learned, also because I have seen many people already talking about it there. Now I really understand it. 👏 But even in C#, a language in which I have worked for about 20 years now, I can relate several examples of monads as well. A nice one are so called LINQ functions, for example SelectMany, which is basically the literal equivalent of your FlatMap example. LINQ is the name of the most important functional programming API in C# and DotNet. Maybe it is also a good to mention that C# was really one of the first with the async await programming model, and it might even be the absolute first one. Though what you mentioned as Future or Promise are not the terms how they are used in C#, but what is used is generally Task or ValueTask, although other types can also be used sometimes.
@sgwong513
@sgwong513 2 жыл бұрын
wow, first time I know monad so clearly. thanks and looking for future video like this. really good video.
@michaelhernandez5478
@michaelhernandez5478 Жыл бұрын
at 4:24 you have a bug. `wrapInLogs` is undefined. I think you meant to assign `a` to `wrapWithLogs`. Other than that... this is the best explanation of the monad pattern in JavaScript ever created on KZbin!
@yash1152
@yash1152 2 жыл бұрын
0:30 thanks a lot for using appropriate font size - readable at 360p. it's such a small thing but makes such a huge impact on viewing experience.
@SteveDellaValentina
@SteveDellaValentina 2 жыл бұрын
I'm not sure how I stumbled on to here but I'm glad I did. This is not only helpful as a software engineer, but a really good example of how to teach an abstract concept in a very accessible way. Very nicely done, and subbed!
@blakedowling7002
@blakedowling7002 Жыл бұрын
Amazing work here. Turns out I've been partially harnessing the power of monads the whole time, but understanding how you can simply chain passed functions brings my software engineering understanding to a new level. Thanks for your effort in making this video Alex.
@nicolaus8622
@nicolaus8622 2 жыл бұрын
Dang. Within only 15 minutes you easily achieved what my professor in functional programming couldn't in an entire semester of 15 weeks lol. No seriously, this video has to be the best explanation for Monads one can find on KZbin!
@IllIl
@IllIl 7 ай бұрын
Bro, you're a legend. I've tried at least a dozen times before this to learn about monads. Wikipedia, googling, videos... was always left with the feeling that even though I didn't get it, the explanations were all trash. This video is so clear, I immediately understood the concept and how it was useful. And some old examples of monads that still rattled around in the skull suddenly made a lot more sense. Thank you.
@mabuelhagag
@mabuelhagag Жыл бұрын
I recently discovered Effect-ts and was struggling to understand the basic concepts of it. The docs don't mention mondas while explaining how the library works (due to a valid reason. Mentioning monads scares people!) But this video explains it beautifully! Thank you man! You got yourself a subscriber 😊
@rajthewise
@rajthewise 2 жыл бұрын
This is the first video that 'shows' the thing by including 'how to' aspect. Best video I came across so far.
@GdeVseSvobodnyeNiki
@GdeVseSvobodnyeNiki Жыл бұрын
The absolutely best and extremely simple and unserstandable explanation of monad was done by Scott Walschin in his F# series. Absolutely must see!
@henningtorsteinsen2169
@henningtorsteinsen2169 Жыл бұрын
Link?
@GdeVseSvobodnyeNiki
@GdeVseSvobodnyeNiki Жыл бұрын
@@henningtorsteinsen2169 that would be a good starting point: kzbin.info/www/bejne/gYHEaYytlLOUrM0si=uabDLykGN5ZCkgbP
@atrowell
@atrowell 2 жыл бұрын
Impressive explanation. Quickly provided useful information that gives me better understanding of techniques I already use as well as new ones to adopt.
@prince_of_devils
@prince_of_devils 2 жыл бұрын
Definitely lives up to the title, thank you for making such a great explanation.
@the-pink-hacker
@the-pink-hacker 5 ай бұрын
Every time I've heard an explanation of Monads I've been completely confused. As soon as I got to the part that mentioned Options, my Rust brain exploded and understood everything. Best video on the topic by far.
@romanmahotskyi6898
@romanmahotskyi6898 2 жыл бұрын
This is one of the best explanations I've ever seen. Thanks a lot
@ryannygard3661
@ryannygard3661 Жыл бұрын
I just made a monad this week without even realizing it, but I never thought about implement logging into it. I'll need to do that immediately because that would be extremely useful!
@marcusjacob9117
@marcusjacob9117 Жыл бұрын
I would pay to get the music turned off. Very distracting. But very useful video, you explain it well.
@tqian86
@tqian86 2 жыл бұрын
This is an amazing intro in the sense that the title isn't even a clickbait! ;) Thanks for the video!
@BrianCameron
@BrianCameron 2 жыл бұрын
The best presentation on Monads I've ever seen... Thank you. Stand alone, does not reference external concepts. Great.
@abdulhamidalsalman
@abdulhamidalsalman 2 жыл бұрын
Alex you are the champion of the web. You deserve a noble prize for making these great videos.
@ethernet764
@ethernet764 2 жыл бұрын
I can’t believe it. I finally understand monads. Thank you! Edit: Please talk about other functional programming concepts.
@AndarManik
@AndarManik 2 ай бұрын
I always feel like monads are explained poorly because FP people don't want to say outright "Monads allow you to have Global access to a variable in languages that don't allow global variables". At some level, monads and recursion have similar problems where educators don't want to explain the concept as the imperative alternative, for example, recursion is most commonly used where explicit iteration is not permitted. Global Variables and Monads provide you the same amount of expressively it's simply a matter of what is available and whether or not using such a thing is worth the complexity. In the first example, the imperative/procedural way of doing that logging solution is to pass in a logging object as a parameter where that object has a log function to take in a string. The functions would then be modified to add the logging side effect. Moreover, if one wanted this change to be smaller you could create a global log object which is always accessable, that way a user can break the "monad" as they please and log only those which they wanted to log, instead of how with monads you'd still have to implement the composition of concatenating empty string in a function which is noise in the code which does nothing. This comes with the extra benefit in that your implementation of the function calls can still be the same as without the logs instead of having to rewrap every function with the monad.
@ShykinArcana
@ShykinArcana 2 жыл бұрын
I've been doing this for years and just calling it good encapsulation and treating functions as a blackbox. Reduce how much the caller needs to know about the function and allow it to be a blackbox. Or rather I suppose, how to create the blackbox in the first place. Good to know the new vocab for it and this is a really good explanation, much better than I could give to new devs. I'd frankly send them to this video to learn the concept.
@denisg1208
@denisg1208 2 жыл бұрын
The way I understood it, monads require a logging of sorts no? Or was that just one use case for monad patterns
@denisg1208
@denisg1208 2 жыл бұрын
Nevermind it was just an example.
@AndreiGeorgescu-j9p
@AndreiGeorgescu-j9p 10 ай бұрын
You've got no idea what you're saying and just saying things lol
@ultimaxkom8728
@ultimaxkom8728 5 ай бұрын
This ain't it, chief.
@Lambda_Ovine
@Lambda_Ovine 2 жыл бұрын
Having watched my fair share of videos, read articles and even delved into some theory behind lambda calculus and functional programming and still not understanding fully what monads are or how to even use them, I was reluctant to watch your video. "There's no way someone can explain monads to me in 15 minutes." I was gladly mistaken. You did the impossible and made monads click for me all the sudden, at least, in a practical way... so thank you very much
@JackDespero
@JackDespero 7 ай бұрын
Just to be nitpicky, the wrapper of the type is not a part of the monad. The (in)famous sentence is true: A monad on A is a monoid of the endofunctors of A. This means that the it is a F: A -> A, meaning that both the original object and the end object must belong to the same category. In your examples, you are doing two different operations: - An isomorphism, F: U -> W, where U are all the unwrapped objects and W are the corresponding unwrapped objects. - A monad, G: W -> W, where the monad acts on any wrapped object and returns the same type of wrapped object. Not that it is fundamental to program or anything, as most of the time combining both is the easiest solution (multiple times my functions accept different types for certain arguments and I internally transform those arguments into the type that I actually use in the function, like passing the name of a matplotlib cmap, and then I get the cmap, but also allowing to pass a cmap itself). Another nitpick to make is that in pure functional programming, the "busy logic behind the scenes" cannot affect anything else other than the object being returned. For example, if instead of adding the log to the object you wrote it somewhere else, that also wouldn't be a monad, even if that function would work exactly in the same way, being able to chain it as much as you want.
@gweltazlemartret6760
@gweltazlemartret6760 3 ай бұрын
Because side effects have side consequences (for real), that goes outside of pure functions. It’s some shady area tho, because adding to a list may have the side effect to increase its memory footprint, pure "pure" functions (on technical side) is barely relevant to most programmers.
@NovemberIGSnow
@NovemberIGSnow 3 ай бұрын
@@gweltazlemartret6760 There's an interesting research language called Koka that uses an algebraic effect system instead of monads. I believe 70% of its stdlib has the "total" effect, meaning those functions: * Are guaranteed to terminate * Are guaranteed to not throw an exception * Do not touch the heap * Do not mutate any state * Do not do IO etc. The total effect is even more restrictive than what a "pure" function in Haskell is. So the fact that a large portion of the standard library can be made of functions with the total effect shows that total pureness is somewhat relevant to programmers.
@trontrontrontron4
@trontrontrontron4 8 ай бұрын
i watch a lot of videos on monads and they always focus on the generic aspect of the monad wrapper, but really this video nails behavior aspects which is what really matters. you can even write monadic code in C using this examples and still have great value using it.
@ocnah
@ocnah 2 жыл бұрын
Absolutely greatly presented and explained, well done.
@gavintillman1884
@gavintillman1884 Жыл бұрын
I’ve been struggling with the concept and think this may be the best presentation I have seen.
@ArturoEspinosaAldama
@ArturoEspinosaAldama Жыл бұрын
This is a nice abstraction, but we should be careful of making sure the performance hit is less than the benefit, and also be careful of unintended, "backstage" byproducts. We should use this pattern only when the advantage of using it would be tremendous, and not only for code to look a little nicer.
@lepidoptera9337
@lepidoptera9337 Жыл бұрын
Can you give an example where it has any advantages at all? Other than being used to show off the giant size of somebody's intellectual balls, that is. ;-)
@yeong126
@yeong126 2 жыл бұрын
Among all the functional programming videos in my feed this is the first one I understand something. Great video!
@AtomicCupcakes
@AtomicCupcakes Жыл бұрын
Thank you so much for making this! I had the Computerphile guy as my functional programming professor and you explained it better than he ever did! What would be interesting is a followup video that ties together what you’ve shown here with the more abstract/mathematical/Haskell notation to fully complete the understanding loop.
@totallycarbon2106
@totallycarbon2106 Жыл бұрын
Ha same! I even got his book. Although I think I did eventually grok it over the course of uni, and I did get into the maths - this was a really nice refresher that's super useful for people actually writing code.
@JMIK1991
@JMIK1991 2 жыл бұрын
Never heard of this, but I can see how to make it in different programming languages now. So it's just any helpful pattern to make code seem simpler while hiding busy works... Knowing this I could make simple program documentations by mentioning for what I would need monad for in the functions... Monad for value that logs itself, gives more programming simplicity, changes value using server connection, changes other program settings to make this one appliable... I guess I could just add reusable lamda functions for functions which process those values, when they are attached to the function, so I need a function to attach them... Now monads would be moddable by programmer aswell at the start of loading the program! So now I got Function class and can create more usable functions for my needs at the start up with less code which behaviour I can change by attaching more functions in it. I can add value to it, it get's processed by all lambda functions I've attached to it, but only one changes it and other uses it to do other stuff. I create function at start up as static and give it a name and attach functions. Now I could just call MyCustomStaticFunction(value) and all lamdas get called internally, perhaps knowing the old value and the new value.. I'd like to use preprocessor function so it would apply code in the binary release in that location instead of going back in memory to that function location, but it's ok for now... Build is smaller, but code also runs slightly slower...
@yellingintothewind
@yellingintothewind Жыл бұрын
I think a large part of the issue explaining Monads is the concept is actually so simple that there is a "why the special name?" question that makes people think it _must_ be more complex. It is a basic function-application pattern, the likes of which you learn the first time you write an async event loop, or implement a DSL-FSM (See Greenspun's 10th rule). And yes, just like the y-combinator, or lambda calculus, it has a basis and explaination in math that makes it look more complex than it really is.
@AndreiGeorgescu-j9p
@AndreiGeorgescu-j9p 10 ай бұрын
None of what you said is true
@aoeu256
@aoeu256 9 ай бұрын
In Javascript Promises/Futures are an example of a Monad, and in that case then is flatMap/ >>=. However, Monads generalize the idea of promises/futures to be able to embed any language with any sort-of semantics into the language, so promises/futures are a way of embedding asynchronous computing into a stateful language and have it look like synchronous code just like monads are used to embed imperative/stateful languages into purely function Haskell. The thing about monads is that you have to know their 5 other definitions and many other examples to see how monads can shorten your code by. You have to know Monads other definition like flatMappables containers where flattenable containers are called Monoids, Mappables are called Functors.
@jamesmstern
@jamesmstern Жыл бұрын
This is a marvel of clarity.
@vladimirvparfenov3935
@vladimirvparfenov3935 2 жыл бұрын
if having trouble understanding the math of this, i really recommend cracking open an abstract algebra textbook. it is not a hard read and you should be able to cover the idea of morphisms between structurally similar mathematical objects within a couple of the first chapters. you could probably even find that some of the homework questions would inspire some good practice exercises for writing some of these patterns
@Psychx_
@Psychx_ 2 жыл бұрын
So this is why Rust has std::option and encourages the use of some/none. Very informative. TYVM!
@robinmoussu
@robinmoussu 2 жыл бұрын
Very nice explanation, and easy to understand. I would just have added that `run` is sometime named `transform` or `map` in other programming languages. That being said, I thought that what you describe is a monadic interface, while modad was the abstraction over those interface. If you can write a modad, you have the same function that take either `Option` or `List` if instead of "stuff may be missing" you want "you may have zero, one or more element". For example Rust has multiple monadic interfaces (`Option`, `Result`, the try operator, `Iterators`, …) but no way to abstract over those so it lack the expressiveness to write a modad. Am I right?
@0LoneTech
@0LoneTech 5 ай бұрын
You could write a monad trait in Rust, and even a macro to implement do notation. Someone did for the monadic crate.
@Daspem25
@Daspem25 2 жыл бұрын
Dude your channel is a gold mine!!
@KiranasOfRizon
@KiranasOfRizon 2 жыл бұрын
Despite having already been exposed to monads through Rust's Option and Result types, your NumberWithLogs example gave me a better understanding of just what all I could use this pattern for. Thank you.
@jfredericks309
@jfredericks309 2 жыл бұрын
NumberWithLogs is not actually a monad, it has the wrong structure to be considered a monad.
@Ca1vema
@Ca1vema 2 жыл бұрын
Err, why function which does some math have to return logs :( There is gotta be a better way to introduce logs into your code 👨‍💻
@itellyouforfree7238
@itellyouforfree7238 2 жыл бұрын
@@jfredericks309 can you elaborate on that?
@jfredericks309
@jfredericks309 2 жыл бұрын
@@itellyouforfree7238 as per the description in the Wikipedia en.m.wikipedia.org/wiki/Monad_(functional_programming) page for Monad, the NumbersWithLogs type is missing one of the defining elements that would make it a monad. There is no function as part of the type that allows different instances Of NumbersWithLogs to be composed. This is the bind or flatMap function which he references in the video but does not implement. You can see this where he stores the results of runWithLogs in variables. If he renamed runWithLogs to flatMap and made it a method on the NumberWithLogs type and removed the first parameter, then it would be closer to a monad. It might then look like this. wrapInLogs(5).flatMap(addOne).flatMap(square).flatMap(multiplyByThree). This would return an instance of NumberWithLogs which you would need to extract the result from. In fact if NumbersWithLogs was made generic say SomethingWithLogs, so the number parameters would all become T, then you have a Writer Monad.
@itellyouforfree7238
@itellyouforfree7238 2 жыл бұрын
@@jfredericks309 At 3:40 he writes the function `runWithLogs`, which is the "bind" function that makes `NumberWithLogs` a monad. There is no need to make it a "method", it makes no semantic difference. He intentionally avoided making `NumberWithLogs` generic to simplify the example. if anything, what is missing is that he never mentioned monadic laws. Those are what makes something a monad, not the name of the functions or whether it's a function or a method.
@Seyunx
@Seyunx 2 жыл бұрын
Topo keep up the amazing work, you deserve more views!
@thezouave7636
@thezouave7636 2 жыл бұрын
If you wanted to implement logging quickly and cheaply, what you'd actually do is have a logger variable that gets passed by reference into anything that is going to log something, and the function does the log. One string construct-write, all writes going to the same place. The logger can even be something as simple as a string array. 8:02 This is a bit more understandable if your language can't pass multiple return values. I still think a templated stuct that has a bool and the raw type would be better, because you can just construct that as a return value and check the bool to see if the result is valid. If you had a modern language that supported multiple returns, you could just return a bool and the raw type, and have a metaprogram check that the success parameter is checked if you need to. 8:22 Undefined is bad, always. Behavior and return values should always be defined in every case. Undefined behaviour is a bug. 8:50 In this example, if you use multiple return values, you can make the "Without Option" code much neater. 9:26 In my opinion, complex things should not be handled behind the scenes. That's how you get slow, inefficient, buggy code especially if you prematurely optimize. To be fair, this is kind of an borderline case. Neatness and abstraction are valueable through apparent simplicity. The design decision every programmer has to make is "how much of a win am I getting here?" and consider alternative methods to achieve a similar result. 10:37 This makes it quite clear how much busywork the computer is doing in the background when the thing you're actually trying to do shouldn't require it. The only win you *might* get, in terms of speed, is if, in the case of Option, something might become nothing at any step of the process. Otherwise you're wasting cycles wrapping and unwrapping things. This is busywork you're making the processor do that it didn't have to. This is SLOW. 11:58 I know enough about multithreading to know this isn't how you want to do it. 13:53 This is also slow, unless you're doing this in a functional language that can do all kinds of calculas on your program to make it go fast. I'd argue that functional laguages have many other downsides that make you not want to use them, but this isn't the place for that. 14:05 Let me rewrite this for you. Monads are a slow design pattern because they let you chain operations with apparent simplicity while hiding work that the processor actually has to do behind the scenes. Final conclusion: This is actually a very well put together and informative video, explaining a very abstract concept in very tractable terms. I would love to see more videos from you on more sensible design patterns. Despite all the hate for monads in this comment, you've done a very good job here Alex.
@warwolt
@warwolt 2 жыл бұрын
Flatmap on an array should not be implemented as a map+flatten, reasonable implementations just directly push the new elements onto the array
@brianistyping
@brianistyping 6 ай бұрын
always know it's a great explanation when it starts with the problem being solved, thanks for the pleasant listen :)
@falin9557
@falin9557 2 жыл бұрын
I didn't understand anything
@defenestrated23
@defenestrated23 7 ай бұрын
Have you tried burrito?
@leisiyox
@leisiyox 7 ай бұрын
That's what monads do to ur brain
@KewalTailor
@KewalTailor 7 ай бұрын
I am proud to say that I kinda did understand it, despite not knowing typescript
@DanteMishima
@DanteMishima 7 ай бұрын
It was the background music, I know
@AdamVollmer
@AdamVollmer 7 ай бұрын
A monad is just a monoid in the category of endofunctors, what's the problem?
@hermaeusmora749
@hermaeusmora749 Жыл бұрын
Hey Alex, thanks for this video. I'm sending it to all my software engineer friends who have heard of Monads but have no interest in figuring out if its actually a good idea.
@Lukilliano
@Lukilliano 2 жыл бұрын
This feels like it would run a lot slower than writing the more complicated code, for example in the option example, if it is already undef in the first functioncall, the rest of the checks if it is undef are not done in the code without the monad, isnt that a issue? Also, the wraping and unwraping feels like it adds more load with many store and load calls, is this fine?
@dewvid
@dewvid 2 жыл бұрын
It's fine because it's a small fixed cost, and can be targeted for optimization. Monads don't cause any of the usual real-world performance impacts: networks, disks, repetition, or a combination of them. Monads enable some optimizations: (1) a promises library may short-circuit the "value already ready" case, in one place so you don't have to do it repeatedly. (2) The "logs" example avoided mutating arrays, which simplifies change detection down to "did the reference change", which is used a lot in the React world to speed things up.
@fluffysheap
@fluffysheap 3 ай бұрын
Real world use of monads normally involves IO, which dominates the time required, or error handling, which is more important than the time taken (and probably faster than exceptions, which are very slow). Then in practice the compiler optimizes many of the seeming redundant operations. In practice monad based code runs quickly.
@Masto12321
@Masto12321 2 жыл бұрын
You won yourself a subscriber with this clean clean video. Can't wait to go through more of your content!
@purovenezolano14
@purovenezolano14 3 жыл бұрын
Great video: Some feedback .. the audio track is a bit distracting iMO .. perhaps lower the volume a wee bit.
@solarisNT-v4j
@solarisNT-v4j 8 ай бұрын
I first grasped monads by thinking of them as piggybanks. The ceramic ones that you have to break. This perfectly compliments that, thank you!
@appelnonsurtaxe
@appelnonsurtaxe Жыл бұрын
I've never programmed in Haskell before but I've heard about that thing where IO is done using monads in order to abstract away the outside world. Since Haskell has no guaranteed order of execution, it's important that functions that perform IO operations somehow depend on the result of operations that should happen before. The abstraction using a monad probably makes this very convenient to work with. Also, in some languages with async programming, I guess you would get the same abstraction as futures, for free.
@Ashalmawia
@Ashalmawia Жыл бұрын
this is the best explanation of monads I've ever seen, thanks
@jaysonbunnell8097
@jaysonbunnell8097 2 жыл бұрын
Awesome vid! So basically, Monads are a way to preserve state without breaking out of the functional programming style. They do this by wrapping values up with some previous state, and acting on it internally (using unwrap or something else). Then the final value will "bubble up". Neat!!
@jonathanlevin7660
@jonathanlevin7660 2 жыл бұрын
Hmmm I think "preservation" of state is the wrong word here, since it implies remembering some history of state If we think of it in terms of state I would think of it this way: * wrapper type: encapsulation of the minimum (current) state, which will be needed by transforms * transform functions: a transformation from one state to amother * run/bind functions: a state machine, but instead of having rules built in, it accepts a dynamic rule to "mutate" the state given to it (Of course no mutation actually happens, it just returns a new value)
@williammorgan2452
@williammorgan2452 2 жыл бұрын
Nice combination of theory and practice.
@deyanvp
@deyanvp 3 жыл бұрын
The diagram with Normal and Monad Land is a bit misleading, as the general recommendation is "once you are in the Monad/Effect Land do not go back & forth to the Normal Land, instead remain in Monad Land and just chain functions using bind/flatMap) ..
@StudyingWithAlex
@StudyingWithAlex 3 жыл бұрын
You're right. You generally stay in Monad Land once entering it, but the function you pass to flatMap/bind takes the unwrapped value. flatMap/bind's job is to unwrap the monad and pass the unwrapped value to this function. That's why you can think of it being unwrapped, albeit temporarily and hidden by the monad.
@isaisotarriva8162
@isaisotarriva8162 5 ай бұрын
This remembers me of my favorite feature of dart, Option (var?). It is beautiful how you can do more if you value can be null or have a value instead of always having to have a value. Using (?) and (!) in dart makes the code much easier to read.
@hiimshort
@hiimshort 2 жыл бұрын
Without a doubt the best introduction to the concept. So many presentations on FP start from a place of mathematics and, while that's great, programmers aren't too interested and also need something more grounded with things they already know.
@joneskamikaze6228
@joneskamikaze6228 2 ай бұрын
never understood monads - until now! thank you!
@adriansrfr
@adriansrfr Жыл бұрын
Interestingly, PowerShell was originally supposed to be named Monad.
@RutgerWillems
@RutgerWillems Жыл бұрын
This is a great vid, but I'm not 100% sure about the example at 9:00. A lot of people will either: - Include the conditional undefined return from the run function inside the JS methods - Want to handle each undefined case slightly differently In the former case, your code would be as clean as #2 without requiring the run wrapper. In the latter you'd end up with #1 where the run wrapper would just add clutter.
one year of studying (it was a mistake)
12:51
Jeffrey Codes
Рет қаралды 225 М.
What is a Monad? - Computerphile
21:50
Computerphile
Рет қаралды 615 М.
The Lost World: Living Room Edition
0:46
Daniel LaBelle
Рет қаралды 27 МЛН
OCCUPIED #shortssprintbrasil
0:37
Natan por Aí
Рет қаралды 131 МЛН
AI Is Not Designed for You
8:29
No Boilerplate
Рет қаралды 349 М.
Reacting to Controversial Opinions of Software Engineers
9:18
Fireship
Рет қаралды 2,2 МЛН
Why Are Scientists Making Robot Insects?
21:16
Veritasium
Рет қаралды 1,5 МЛН
The Perfect Dependency - SQLite Case Study
19:32
Tom Delalande
Рет қаралды 90 М.
How Senior Programmers ACTUALLY Write Code
13:37
Thriving Technologist
Рет қаралды 1,6 МЛН
Programming with Math | The Lambda Calculus
21:48
Eyesomorphic
Рет қаралды 256 М.
Microservices are Technical Debt
31:59
NeetCodeIO
Рет қаралды 748 М.
Coding Was HARD Until I Learned These 5 Things...
8:34
Elsa Scola
Рет қаралды 878 М.
7 Years of Software Engineering Advice in 18 Minutes
18:32
The Lost World: Living Room Edition
0:46
Daniel LaBelle
Рет қаралды 27 МЛН