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!
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...
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).I'm favoriting this comment so I can come back the next time I forget how all this works :)
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.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.What's the difference?
I once spent a day thinking I had misunderstood something fundamental, but really I just had an errant tab instead of a space.
The number of times I've used curly braces, single lines or expression substitution to bail me out is many...
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
"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 .
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?
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...
In imperative steps of code, time flows down your code.
In functional code your flow of time is each function application.
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?
- 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
That's what the free monad does. Not every monad is a free monad, IO certainly isn't.
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.
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.
https://hackage.haskell.org/package/base-4.14.0.0/docs/src/G...
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.