News for hackers. Stuff that matters.
Re:Inventing Monads by ridiculous_fish on Saturday August 29, 2020 @03:57PM (#24318962)
> This begins to get us to the fundamental abstraction of a monad: a box, with an interface for map, and flatMap

Before I understood monads, I read variations of the above sentence a million times, always got stuck here: https://i.imgur.com/McThkuh.png

How does this abstraction let us perform IO, do in-place destructive updates, etc? The answer is that it doesn't. These must be primitives supplied by the runtime. A monad like IO has its two functions (return+bind), and a bunch of other magic functions. It's obvious now but that fact is hardly ever stated.

I wonder if anyone has tried explaining from the other direction? Rather than building up to Maybe, try building down from a desire to print Hello World.

Re:Inventing Monads by anchpop on Saturday August 29, 2020 @04:19PM (#24319137)
What you say is correct, but let me try and explain a little further. The Haskell function `getChar` is used to get a character from stdin. It has the type `IO Char` and is a totally, 100% pure. In fact, it isn't even a function, it's just a value.

You can write `getChar` as many times as you want, and you will get the same result every time, and it will have nothing to do with whatever character is being sent to stdin. Instead, what you will get is an instruction, saying "please get a character from stdin".

What the IO monad allows you to do is to compose instructions together. For example, you could write `getChar >> getChar". This makes a new instruction that says "please get a character from stdin, discard it, then get a character from stdin". The `>>` operator means "follow the instruction on the left, discard the result, then do the instruction on the right".

Your entire program is made by composing instructions like this, into one new huge instruction that specifies your entire program's behaviour. You assign that to the special name `main`. At runtime, the instruction is executed.

The only bit of compiler magic that's necessary is the code for interpreting the instructions and actually executing them. In theory, although haskell doesn't let you do this, you could write `getChar` yourself, and just return the same thing that `getChar` does, and it would behave identically.

This I feel is the simplest explanation for why monads are necessary in Haskell. They allow you to conveniently specify what you want your program to do, using only pure functions and values. Why do you want all values to be pure? Many don't because it's kind of a pain, but Haskell kind of exists to see if a lazy, pure functional language can be fun to use and many find that it is. Hope this helps someone!

Re:Inventing Monads by ridiculous_fish on Saturday August 29, 2020 @05:06PM (#24319435)
Great description of IO, but I think it doesn't actually motivate monads. Your example of `getChar >> getChar` could be simply `[getChar, getChar]`. Why can't we just compose instructions into an ordinary list?

The answer is that we can, and Haskell used to work this way [1]! So as 'chowells' observed the monad-part of IO is almost incidental.

1: https://stackoverflow.com/questions/17002119/haskell-pre-mon...

Re:Inventing Monads by a1369209993 on Saturday August 29, 2020 @08:28PM (#24320386)
> Your example of `getChar >> getChar` could be simply `[getChar, getChar]`. Why can't we just compose instructions into an ordinary list?

Because you can't pass results from a earlier list element into the computation of a later element. You'd need a list with existentially-quantified element types such as:

  {-# LANGUAGE ExistentialQuantification, GADTs #-}
  foreign import ccall "exit" exit :: Int -> IO ()
  infixr 1 :>

  data IOList a = forall b. (:>) (a -> Act b) (IOList b)
  data Act b where
    Getchar :: Act Char
    Print :: String -> Act ()
    Exit :: Int -> Act ()
  
  main' :: IOList ()
  main' = (\_->Getchar)
       :> (\c->Print ("Got '"++[c]++"'\n"))
       :> (\_ -> Exit 0)
       :> undefined
  
  runio :: a -> IOList a -> IO ()
  runio a (f:>fs) = flip runio fs =<< case f a of
    Getchar -> getChar
    Print s -> putStr s
    Exit n -> exit n
  
  main = runio () main'
where f :> g :> h :> ... is your list of instructions (rather than f : g : h : ..., which doesn't allow the response type of f to be related to the argument type of g).
Re:Inventing Monads by thatcherc on Saturday August 29, 2020 @05:14PM (#24319483)
Ah, thanks - this is a really nice explanation. From reading a few "what is a monad" posts in the past, I get how the a monad can chain functions in sequence for imperative-style execution, but how the information like 'getChar' actually got in was never clear. It all comes down to the runtime I guess.

I'm favoriting this comment so I can come back the next time I forget how all this works :)

Re:Inventing Monads by roenxi on Saturday August 29, 2020 @11:32PM (#24321148)
Although true; I'm not sure much of that provides clarity. Eg, "Your entire program is ... one new huge instruction" - that is true of any program, and it doesn't sound like a useful abstraction for reasoning about programs. The idea that getChar returns an instruction rather than a character is similarly not an obvious improvement from getChar() returning a character. It is quite subtle for someone to complain that getChar() returning a char is suboptimal.

Everything I've seen is monads are confusing because they solve a problem imperative languages don't think they have. As the article points out,

  function getDisplayPictureFromId(id) { 
    const user = getUser(id)
    if (!user) return
    const profile = getProfile(user)
    if (!profile) return
    return getDisplayPicture(profile)
  }
is totally fine and idiomatic in most imperative languages. Once a programmer starts chaining functions together (as functional programmers are wont to do) then the "if (!user) return" become a substantial blocker that needs a solution - which leads very quickly to monads and abstracting away IO.
Re:Inventing Monads by brabel on Sunday August 30, 2020 @04:48AM (#24322213)
That's not fine and idiomatic in any language I know.

This would be:

    function getDisplayPictureFromId(id) {
        return getUser(id)?.profile?.displayPicture
    }
If the language does not have the null-safe operator '?.' you just write it:

    function nullSafe(obj, callback) {
        if (obj) {
            return callback(obj)
        }
        return null
    }
    function getDisplayPictureFromId(id) {
        return nullSafe(getUser(id),
            (user) => nullSafe(user.profile,
                (profile) => profile.displayPicture)
        ))
    }
Not as nice in this case, but with a few similar functions for composing other functions, you achieve similar benefits to Monads without having the complexity of higher-kinded types.
Re:Inventing Monads by choeger on Saturday August 29, 2020 @04:52PM (#24319345)
> In fact, it isn't even a function, it's just a value.

What's the difference?

Re:Inventing Monads by dllthomas on Saturday August 29, 2020 @05:09PM (#24319458)
Functions are values, but values that are not functions are those that cannot be supplied an argument.
Re:Inventing Monads by chowells on Saturday August 29, 2020 @04:06PM (#24319033)
I think most of this happens because lots of people say things like "the IO monad" when they actually just mean "IO". It misleads people into thinking the monad part is important. It isn't. IO is the tough concept. Monad is almost trivial.
Re:Inventing Monads by ridiculous_fish on Saturday August 29, 2020 @04:17PM (#24319113)
Good point, I agree. But you must learn it to get anything done. Grappling with IO + monad + do-notation all at once is hard!

I once spent a day thinking I had misunderstood something fundamental, but really I just had an errant tab instead of a space.

Re:Inventing Monads by chowells on Saturday August 29, 2020 @05:37PM (#24319600)
Ok, yes. Monads as a concept are almost trivial in comparison to thinking in terms of the IO type. But that doesn't mean they are easy and don't add more hurdles to get over. I think I undersold how daunting it can be to face all the new things at once, and you're right about it.
Re:Inventing Monads by yomly on Saturday August 29, 2020 @05:53PM (#24319686)
As a recent Haskell learner, I found the indentation part of Haskell hard to learn and a little undiscoverable/hard to google.

The number of times I've used curly braces, single lines or expression substitution to bail me out is many...

Re:Inventing Monads by neckardt on Saturday August 29, 2020 @09:35PM (#24320642)
You might like hinc, it's haskell but with C style syntax: https://github.com/serras/hinc/blob/master/why.md
Re:Inventing Monads by yomly on Sunday August 30, 2020 @05:28AM (#24322343)
Thanks for the suggestion but Haskell would not be Haskell without its ML-yness.

As confusing as operator precedence can get, I do see the beauty in "programmable whitespace" but to get anywhere close in other language syntaxes you need to do even more perverse things like here [1]

If I did have to choose a different syntax for haskell it would be S-expressions rather than Algol so perhaps Hackett from Lexi Lambda

[1] https://stackoverflow.com/a/48553568

Re:Inventing Monads by scns on Sunday August 30, 2020 @02:01AM (#24321669)
I like it.

"This is not by coincidence: people learning Haskell usually have problems with point-free style not because of the composition operator per se, but because code is suddenly "reversed". Other communities such as F# have adopted the "pipe forward" operator instead of composition as the default style."

That's why i prefer the reverse application operator & to .

Re:Inventing Monads by dllthomas on Saturday August 29, 2020 @05:10PM (#24319466)
+ type inference + return-type polymorphism!
Re:Inventing Monads by goto11 on Saturday August 29, 2020 @05:29PM (#24319565)
Yeah this is like saying objects lets us perform IO in Java, and then going deep into explanations of what objects are and what rules they obey (Liskov substitution principle etc) - instead of just explaining that you call println() to write "hello world".
Re:Inventing Monads by yomly on Saturday August 29, 2020 @05:50PM (#24319672)
We often forget how much assumed knowledge (and accepted knowledge) went into learning OOP.

Turing Machine and Lambda Calculus are two entry points into computational thinking, is it really so alarming that if you've only learned one that trying to learn the other will make you feel like a beginner all over again?

Re:Inventing Monads by Izkata on Sunday August 30, 2020 @04:53AM (#24322236)
Y'know what, maybe looking at it like that is actually one of the problems: We don't learn our first imperative language(s) by way of Turing machines. That theory-level understanding comes much later, after we have a handle on the language itself.

When first learning, the most common abstractions are variations on "a list of steps" - like an instruction manual or To-do list - without touching on memory.

I wonder if there's some sort of similar abstraction here that could be used instead, for the just-getting-started stage...

Re:Inventing Monads by yomly on Sunday August 30, 2020 @05:32AM (#24322353)
Excel function pipelines which take inputs to outputs. People build wonderfully useful things in Excel using its standard library of spreadsheet functions. They are all referentially transparent.

In imperative steps of code, time flows down your code.

In functional code your flow of time is each function application.

Re:Inventing Monads by goto11 on Sunday August 30, 2020 @01:00PM (#24324101)
This is what I call haskellsplaining - explaining concept from first principles and mathematical definitions rather than from how they are used and what they are useful for.
Re:Inventing Monads by smitty1e on Saturday August 29, 2020 @07:09PM (#24320057)
I think the sticky wicket with Haskell is less the terse syntax and more the execution model.

Why not start enumerating the lines of a file, and show how we're building up a list of thinks, and there is no actual variable representing the line numbers because state is for Statists?

Re:Inventing Monads by smitty1e on Sunday August 30, 2020 @05:05AM (#24322278)
Thunks
Re:Inventing Monads by navaati on Sunday August 30, 2020 @10:54AM (#24323308)
Thanks
Re:Inventing Monads by agumonkey on Saturday August 29, 2020 @04:32PM (#24319221)
to me the issue is twofold:

- cultural reliance on lambdas as the universal force (nothing against lambdas, but outside the fp world, there will be too much culture shock)

- representation as computation, the monad is only kinda building a graph to be evaluated, and each node can be wrapped with rules as you see fit

Re:Inventing Monads by 08-15 on Saturday August 29, 2020 @11:31PM (#24321145)
> the monad is only kinda building a graph to be evaluated

That's what the free monad does. Not every monad is a free monad, IO certainly isn't.

Re:Inventing Monads by edflsafoiewq on Sunday August 30, 2020 @12:23AM (#24321351)
Why isn't IO free?
Re:Inventing Monads by 08-15 on Sunday August 30, 2020 @02:52AM (#24321833)
Come think about it, it could be. That's not how it's implemented in any Haskell implementation I know of.
Re:Inventing Monads by AnimalMuppet on Saturday August 29, 2020 @06:27PM (#24319852)
Hmm. Your last line makes me think that they're, essentially, using monads to represent S-expressions. That seems... somewhat clumsier than just using S-expressions. You gain a really good type system, though.
Re:Inventing Monads by agumonkey on Saturday August 29, 2020 @06:59PM (#24320020)
I'm so not an expert I hope people don't read me too seriously. It's just my understanding of the FP world. A lot of time they will encode ideas in threaded closures that do nothing until they're consumed (the programmable semicolon doing the 'interpretative' part) which is a bit like a DSL tree and not so removed from a ~lisp.
Re:Inventing Monads by scns on Sunday August 30, 2020 @02:03AM (#24321677)
Hopefully Java programmers are used to lambdas since Java 8
Re:Inventing Monads by agumonkey on Sunday August 30, 2020 @03:00AM (#24321857)
It's not the same context really. A lot of languages have lambdas, and had before Java such as js, python.. but in these languages, it was an obscure feature.

In lisp/fp it was the "only" feature. People were thinking in how to encode anything with lambdas and not with the usual imperative traits (prog, do, loop). Consider that in 75, the first scheme paper was already talking about CPS (aka pre-monadic style).

I'm not making value judgement, it's just that using parameterized code blocks in LINQ select/where or java streams or python map/reduce is just the very first step in a long series of stairs. And monads are on the 3rd floor kinda.

So to the fp crowd it's business as usual, but for the rest of the world it's a twisted idiom at first.

Re:Inventing Monads by raiflip on Saturday August 29, 2020 @04:18PM (#24319130)
A monad really is just a wrapper around a value, with flatMap and return.

For some kinds of monads, like maybe, that’s all you need.

But, some other kinds of monads need more logic. List is one, IO is another.

In OOP language, sometimes all you need is the parent class. But sometimes you need to extend the parent and add more.

Re:Inventing Monads by ratww on Saturday August 29, 2020 @06:40PM (#24319923)
It's actually more like an abstract class! Even the Maybe monad has some implementation, it's just super simple :)

https://hackage.haskell.org/package/base-4.14.0.0/docs/src/G...

Re:Inventing Monads by raiflip on Sunday August 30, 2020 @10:48AM (#24323277)
Totally agree, that’s a good point.