Hacker News new | ask | show | jobs
by ratww 2392 days ago
> hey, you know if you have a purely functional language, it would be impossible to have IO, since e.g. a read function would have different outputs every time. We solve that with monads. But that didn't feel like an explanation.

In a pure language you can’t have functions that return the contents of a file, or prints to stdout, or anything like that.

So what do you do? Instead of performing those computations in you program, you have to return (in the main function) a bunch of lambdas chained together that will be executed by the runtime that called the main function in the first place. Inside this chain of lambdas you will probably call the rest of your program.

The Haskell function you can call that “prints a string” doesn’t do much: it just returns some dummy structure (similar to an AST node, but you can chain your pure functions there too!) that will be read and executed later by the runtime. All the work is done later!

Your “main” in Haskell returns immediately, it doesnt do much. It does zero IO.

This is similar to how promises work in JavaScript: you return a structure instead of the result. Also similar to how React works (If you know its internals) but don’t let that distract you!!!

This is how the IO monad works.

People later discovered that this kind of structure could be used to a lot of stuff, and other monads (State monad, Maybe monad, Free monad) were born.

But these others don’t use the IO runtime.

Also look up “functional core imperative shell”, this is how IO monad and the IO runtime works.