24 points · by herodotus · 5y ago · 54 comments
In the article itself, the line:
> As it happens the computation will need the value of b before that of a. If this is a problem, we can write the definition of root1 as
Is actually quite interesting: the problem being described there is almost identical to one of the problems that Haskell had with I/O, which motivated the introduction of monads.
main = do { putStrLn "Hello, World!" ; return () }
The code should read like this instead (and I think the linter would suggest this): main = putStrLn "Hello, World"If you just needs a fixed set of inputs without dependencies, conditionals, branching etc you indeed don’t need monads.
The consensus of many highly intelligent people knowledgeable on the subject seems to be monads allow you to maintain a pure language while performing IO. This shouldn’t make it an incontestable fact, but probably should make disagreement worth more than a throwaway line — that is if you want to avoid looking like a crackpot.
Many are of the position that the IO monad is purely a type theoretical hack that allows one to control the order of effectful functions in Haskell that under the surface creates a vacuous data dependency that ensures the optimizer must sequence them in a particular order.
There is no consensus as to what the IO monad “is”; only what it's specific semantics with regard to execution order is.
But it serves it's purpose in that allows one to control the order of certain effects in another wise non strict language while semantically not necessarily relying on controlling the order of execution of function calls.
On the type level, the effect of the function is separated from the calling of the function and it's effect need not necessarily take place conceptually when the function be called; under the hood, it simply ensures that the optimizer cannot move out of order the effectful kernel of the function by way of this vacuous data dependency.
{-# LANGUAGE GADTs #-}
data IO' a where
Pure :: a -> IO' a
Bind :: IO' a -> (a -> IO' b) -> IO' b
PutStrLn :: String -> IO' ()
GetLine :: IO' String
-- more IO operations…
instance Functor IO' where
fmap f ma = Bind ma (Pure . f)
instance Applicative IO' where
pure = Pure
mf <*> ma = Bind mf (\f -> Bind ma (Pure . f))
instance Monad IO' where
(>>=) = Bind
The actual implementation in GHC is much more efficient, of course. GHC does all sorts of magic to hide the fact that it’s generating straight-line code instead of a tree-like data structure full of continuation functions. But it’s semantically equivalent.An IO action describes what to do, but something still has to do that action. A Haskell program on its own doesn't do anything; that's exactly why it's pure. The Haskell runtime interprets an IO value, unraveling it into the string of commands that comprise it. The runtime executes the commands produced by the Haskell program.
Haskell uses monads exactly because it lets you describe/express complex sequences of actions (for which later actions depend on earlier actions) without requiring that the machinery for actually performing those actions be part of the program too.
You have described the typological constraints the IO Monad conforms to, but you have not actually implemented any functions in it.
That is why some are of the position that it is merely a type system hack that fools the type system into thinking that it is pure as any other, whereas under the hood it requires coöperation from the optimizer with vacuous dependencies to ensure that all executions happen within the specified order.
The axiomatic functions of the IO Monad have to be provided as primitives by the compiler, they cannot be written as a purely library function, unlike, say `||` in Haskell which can actually be realized as a library function unlike in most languages where it must be a specially treated primitive.
If you define your own type called IO you can't use it to execute unpure operations.
I/O is by definition not pure, but the use of monads allow a strict separation between the pure and impure parts of the code. I guess you can say that monads allow you to have a guaranteed pure sublanguage.
The whole premise is that you end up with some main function which is a description of side effects, but you still have referential transparency and the like at a language level (so I/O doesn't need special treatment).
(there's a whole thing about "monad = IO" in laypeople discussion of Haskell which I think muddies this. There are loads of monads not about doing side effects, like list. But instead people think there's a link between monads and side effects, because we say "IO monad" instead of just "in IO" or something)
EDIT: it's v true that like.... side effects are side effects are side effects, so you can take that shortcut when talking about stuff. But if you want to get into the details about whether some expression is pure or not, you're brushing up against important semantics!
main = do
putStrLn "Hello, what's your name?"
name <- getLine
putStrLn $ "Hello " ++ name
And one in JavaScript: function main() {
let name = prompt('Hello, what is your name?');
alert('Hello, ' + name);
}
My claim is that either both have side effects or neither. In both cases the definition of a function does not in itself have side effects, and the function can be passed around and manipulated without being executed. But when the function is executed, it causes side effects.Haskell have the feature that the type system can statically verify if functions are pure or not. This is very cool, but it does not change the semantics or purity of a function, it just verifies it statically.
Edit: sorry I glossed over the last bit regarding a sub-language. The point is the whole language is considered (at least by many of its proponents) pure: monads + runtime + FFI are the gymnastics that allow one to perform IO in a pure language.
main = do
putStrLn "Hello, what's your name?"
name <- getLine
putStrLn $ "Hello " ++ name
is not pure in any meaningful sense. At least not any more pure than the similar code in any other language.If you can’t, then this only solves a rather limited subset of I/O, where the program is essentially a pure function whose input is the set of answers to a fixed set of prompts. It’s sufficient for some use cases, but most real programs need more interactivity than that.
If you can depend on prior inputs, on the other hand, then input() is not pure. Simply evaluating it has the side effect of displaying some text to the user.
(Arguably this would be true even if the prompt couldn’t depend on prior input, as long as it was the act of evaluating input() that caused the prompt to appear. An alternative would be to treat input() as a sort of macro, where the interpreter statically analyzes the program to determine every prompt for every input() call that could possibly be made, asks the user up front for responses to all of those, then, when input() is actually evaluated, just looks up the already-entered response. That would make input() pure. And maybe you could argue that even if input() does display a prompt only at the time it’s evaluated, it’s sort of morally equivalent to what I previously mentioned, just saving time by not asking unnecessary questions. But that goes out the window if questions can depend on prior answers.)
My feedback regarding the design goals: As a working functional programmer, I find monads to be extremely helpful in many scenarios, I use them as much for validation, business logic, and parsers, as I do for IO. I also like how easily monads can be used to handle async with the same syntax as synchronous IO. Though I haven’t used Haxl yet, I find the idea of using applicative functors for free/automatic parallelism really interesting; I gather that a contributing factor for this being somewhat straightforward is because applicative is a superclass of monad. I also don’t believe monads are actually that complicated, just a scary name and many poor explanations floating around. All of this is to say I don’t find the design goals of eliminating monads very compelling.
The desirable properties that we are trying to enforce are that, firstly
x = expression
y = expression
...
is the same as x = expression
y = x
...
and that, secondly x = expression
...
is the same as ...
when x does not appear in ... .These conditions are an order of magnitude more important than any considerations about what "purity" really means, what side effects are versus effects, whether there's an impure runtime below a pure language and whether IO is a "sublanguage".
They can also assist in decoupling code from side-effects, while keeping code simpler and coherent. Like with Go, just more subtly, it seems Haskell directs the programmer towards better code design, by giving helpful errors from the type system. This is because the types ensures that you avoid mixing what should not be mixed. If there's alot of errors and progress is slow, this is to be expected at startup, as you will be directed to find the better code structure to build your shell on. Once the shell is more complete, it will be easier to incorporate the functional core in that, or vica versa. So in that area also, it is helpful and useful, once one groks the hints of linter and compiler errors (use an IDE for this).
[1] Impure as per https://news.ycombinator.com/item?id=27259900
Seems like the author doesn't understand what's going on.
He's a well-known language designer, famous for his work in dataflow, whose work was influential in the field. We should ask him to explain what he meant by that, before jumping to internet cheap shots.
It looks imperative because that's what Haskell's do-notation was designed to. But it's merely syntactic sugar for the functional equivalent
main = putStrLn "Hello, World!" >> return ()
which btw is equivalent to simply main = putStrLn "Hello, World!"If the author really doesn't like the "imperative" syntactic sugar then it's always possible to write equivalent code without it, but it quickly becomes painful for more complex situations.
'do notation' is just a more generalised version of what async/await does. No one wants to go back to writing async code with callbacks / continuations.
While it is true that they yield the same result back to the program on each invocation, so would OCaml invocation `Printf.printf "Hello, World!"`, it namely always returns `()`, but it is quite an effectful function, of course.