NHacker Next
login
▲Monad Tutorials Timelinewiki.haskell.org
60 points by brudgers 9 hours ago | 22 comments
Loading comments...
preommr 6 hours ago [-]
To explain like two fundamental rules (we can make wrapper types, and do flatmap) I will:

- Write 5 paragraphs setting up an imaginary scenario involving fantasy elements of aliens, dragons, and a magical kindom where they speak using message boxes

- Introduce basic category theory by starting with what a functor is

- Explain all the effects of a monad in such general terms that it basically amounts to anything and everything - since a function can be anything and do everything and it's just function composition

- Write some snippets of Haskell, and just assume that you're familiar with the syntax

- Talk about how delicious burritos are

alper 4 hours ago [-]
I've read more than my fair share of these tutorials, and I'd like to be proven wrong here but I don't think I've ever seen one that explains what the point of these functional constructs (similarly with Applicative etc.) is.

"You can do IO now." So what? I could do IO before that as well.

Very rarely are practical explanations discussed. Even if they are discussed, the treatment is shallow and useless.

lmm 3 hours ago [-]
Here's my effort: https://m50d.github.io/2013/01/16/generic-contexts
amenghra 3 hours ago [-]
From the very beginning of the article (level 1), I don't see what's wrong with code that looks like the following. Early return seems to fix the "typing this makes me feel ill" part? To me, the following code seems perfectly readable without requiring the reader to know about function composition.

  def doFunctionsInSequence1(): Option[Set[Int]] = {
    val r1 = f1(null)
    if(r1.isEmpty) {
      return None
    }

    val r2 = f2(r1.get)
    if(r2.isEmpty) {
      return None
    }

    return f3(r2.get)
  }
lmm 2 hours ago [-]
I find that pretty repetitive, but more, having to reason about branching control flow adds a lot of mental overhead that I'd rather spend on my business logic.
w4rh4wk5 3 hours ago [-]
From my experience having used Haskell (a long time ago), the main benefit of Monads is the `do` and <- syntax. Once you got your thing to satisfy the Monad interface, you unlocked the nice syntax for writing code. That, and compatibility with transformers.

Whether this is the best thing since sliced bread or not, is left as an exercise to the reader.

codebje 19 minutes ago [-]
Hah, I like that: the main benefit of monads is turning your functional language back into an imperative one...

IMO it's because option is a monad, list is a monad, io is a monad, async is a monad, try-except is a monad, why invent different magic syntax and semantics for all of them when there's a perfectly good abstraction that covers the lot, and that lets you write functions that are agnostic to which particular monad they're in to boot.

hypendev 2 hours ago [-]
A joke says that its because once you get it, you lose the ability to explain it like a normal person :)

And another joke says the best way to explain a monad tutorial is to write another one, so sorry for this.

Just think of it as a box.

If amazon sent items themselves, it would be hard to pack, no way to standardize, things would break often or fall out of their respective boxes.

Now, if you put it into one of the standardized boxes, that makes things 100x easier. Now you can put these on a conveyor belt, now you can have robots sorting these, now you can use tape to close them, standardization becomes easy as it's not "t-shirt,tennis ball,drill" but just "box box box".

So now you can do all kinds of things because it's all a box. And you can also stress test the box.

It's the same with these.

A. You can just have a function that: calls a something on IO, maps it's values, does a calculation, retries if wrong, stores the result, spits it out.

Or B. you can have functions that calls any function on IO, functions that map any value to any other value, functions that take any other function and if that function fails calls another function or retries, one that stores any value given to it and returns with information if it saved or not etc.

The result is the same in the end, but while 1 makes the workflow be strictly defined only for that case, and now you have to handle every turn and twist manually (did the save save? what if not? write a check, write a test that ensures its not and the check works, same if it does...) the 2 lets you define workflows with pre-tested, pre-built blocks that work with any part of your codebase.

And it makes your life 1000x easier because now you have common components that work with any data type inside your codebase, do things your way always, are 100% tested and make it easier to handle good cases, bad cases, wiring and logistics. And you can build pipelines out of them. Because at the end, what it does is just lets you chain functions that return wrapped values.

And you end up with code like:

val profileData = asAsync { network.userData(userId) } //returns a Async<Result<UserData, Error>

.withRetries(3) // Works on Async, and returns Result, retries async if fails

.withTraceId(userId) //wrapped flatmap that wraps success into Trace<T> and adds a traceId

.mapTrace(onError = { ErrorMappingProfile }, { user -> Profile(user.name, user.profileId) } // our mapTrace is a flatMap for Trace objects, so it knows how to extract trace objects, call the functions and wrap them again

.store("profile_data") //wrapped mapCatching again for storage explicitly that works on Trace objects, knows how to unwrap them, stores them,

.logInto(ourLogger) // maps trace objects into shared logger

Each of these things would before have to be manually written inside the function, the whole function tested for each edge case. if/else's, try/catch, match/when/switch.

This way, only thing you need to cover with tests now is `network.userData()`, as all other parts are already tested, written and do what they say they do. And you can reuse this everywhere in your projects. Instead of being a function you call with data, it becomes a function you give a box and it returns a box. Then you can give it to any other function that needs a box. If boxes make no sense, think of the little connectors on lego bricks, or pipe connectors in plumbing, or stacking USB adapters or power strips.

I can't stress enough how much this approach helped me in real life cases - refactoring old codebases especially, as once you establish some base primitives, the surface area starts massively collapsing as the test surface area increases.

jappgar 2 hours ago [-]
Haskell is primarily a bunch of type gymnastics designed to give the impression of "purity" when no such thing exists in the world.
gnabgib 9 hours ago [-]
It's an updating wiki.. but (2017) https://news.ycombinator.com/item?id=15170328

Popular well.. submissions in:

2019 (3 points) https://news.ycombinator.com/item?id=19207241

2022 (3 points) https://news.ycombinator.com/item?id=30277518

2024 (11 points) https://news.ycombinator.com/item?id=40332349

cubefox 5 hours ago [-]
I understood the monad concept for a few months in university. After the exam was over, I soon stopped understanding it. The same thing happened with the concept of VC dimension. It's kind of interesting, because we usually don't think of "understanding" as something that comes with a time limit.
alper 4 hours ago [-]
It happens all the time. For a brief period I understood musical notation and rhythm and then it was gone. Similarly I had a time in my life where I knew by feeling whether a French noun was le or la.
cpa 7 hours ago [-]
Pretty cool!

I've spent a lot of time wrapping my head around monads; whenever I thought I "got it," I would come across some exotic monad that completely blew my mind. The best way to understand them is not to rely on analogies but just follow the rules—everybody says that, but it took me a while to truly realize it.

See, for example, the Tardis monad or the Cont monad: https://www.reddit.com/r/haskell/comments/446d13/exotic_mona...

ducklord 4 hours ago [-]
I tried understanding the rules but actually using it helped me to get it. Especially when I was using a parser combinator to parse a programming language.
7 hours ago [-]
armchairhacker 4 hours ago [-]
I still don’t understand why it’s named from Gnosticism (https://en.wikipedia.org/wiki/Monad_(Gnosticism))
yccs27 4 hours ago [-]
Monads got their name from monoids (being a monoid in the category of endofunctors). Monoids are equivalent to one-object categories, so the name uses the greek syllable "mono" for one.
intrinsicallee 3 hours ago [-]
It comes from Pythagoras, not Gnosticism
urxvtcd 4 hours ago [-]
Yeah, would like to know as well. I think the applicative functor was originally call "Idiom", another weird name.
4 hours ago [-]
FrustratedMonky 1 hours ago [-]
A good explanation I read once.

That the best way to understand Monads, was to write a Tutorial about Monads.

Which does make sense. To understand a subject, the best way is to teach the subject.

ReptileMan 1 hours ago [-]
I have always thought that monads are just side effects and that's it.
Dig1t 6 hours ago [-]
So weird, on the front page at the same time as this: "Biology is a burrito"

When I saw that link it immediately reminded me of this: https://blog.plover.com/prog/burritos.html

>Monads are like burritos

And then a few links down is this link to monad tutorials.

Weird coincidence.

ducklord 4 hours ago [-]
> Monads are like burritos https://blog.plover.com/prog/burritos.html

I'm surprised that this tutorial isn't on the wiki.