News for hackers. Stuff that matters.
Re:Monads Schmonads: Functional Input Without Tears (PYFL) by Blikkentrekker on Sunday May 23, 2021 @06:03PM (#27259039)
That's not a consensus at all.

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.

Re:Monads Schmonads: Functional Input Without Tears (PYFL) by anderskaseorg on Sunday May 23, 2021 @06:31PM (#27259246)
It’s easy to demonstrate that the IO monad is pure by reimplementing it in 100% pure code.

    {-# 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.
Re:Monads Schmonads: Functional Input Without Tears (PYFL) by Twisol on Sunday May 23, 2021 @06:52PM (#27259369)
You're right, but I think there's a distinction here that is easy to miss.

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.

Re:Monads Schmonads: Functional Input Without Tears (PYFL) by anderskaseorg on Sunday May 23, 2021 @08:35PM (#27259967)
That would be equally true of a programming model where every program is a pure function from a list of input lines to a list of output lines. Everyone would agree that such a model is pure (if limiting), even though the function itself is just a function, and the language runtime takes care of the ugly low-level details of actually making the system calls that read lines from STDIN and write lines to STDOUT.

Purity doesn’t mean that effects don’t happen. It means that effects don’t happen as a side effect of mere expression evaluation.

Re:Monads Schmonads: Functional Input Without Tears (PYFL) by Twisol on Monday May 24, 2021 @12:36AM (#27261110)
> Purity doesn’t mean that effects don’t happen. It means that effects don’t happen as a side effect of mere expression evaluation.

I don't disagree? I was adding color to your explanation for other readers, not attempting to correct you.

The evaluation of a program merely reduces or simplifies it, transforming its structure without adding or removing information. When we can't reduce further without interacting with the environment, something else must mediate that interaction.

> That would be equally true of a programming model where every program is a pure function from a list of input lines to a list of output lines.

Indeed, Haskell used this model (`[Request] -> [Response]`) before switching to use an IO monad. It made for a poor architectural basis for complex programs.

Re:Monads Schmonads: Functional Input Without Tears (PYFL) by goto11 on Monday May 24, 2021 @04:34AM (#27262176)
But isn't it the case in any programming language that impure operations only have side effects when they are executed? You might as well argue that a JavaScript program on its own is pure - it is only when it is executed by the runtime it has side effects.

You can also pass a function around without executing it in JavaScript.

Re:Monads Schmonads: Functional Input Without Tears (PYFL) by pwm on Monday May 24, 2021 @05:29AM (#27262471)
A good mental model is that Haskell has expressions that are evaluated and JavaScript has statements that are executed.

  const io_actions = ["hello", "world"].map(s => console.log(s));
  io_actions[1];
vs.

  io_actions = map putStrLn ["hello", "world"]
  main = io_actions !! 1
JS will print out "hello" and "world" and the value of io_actions[0] is undefined. In Haskell, the value of io_actions !! 0 is IO "world" which is just a value you can pass around in your program. Only when the Haskell runtime evaluates your code is when it will do the effect, which is to print "world". "hello" is never printed.

Naturally you can also pattern match on IO ():

  f :: IO ()
  f = case putStrLn "hello" of
    _ -> putStrLn "world"
also only prints "world".

The IO type in Haskell is akin to IO (State World -> (State World, a)), ie. the state monad where the state threaded through the computation is the "real world". This can be demonstrated with the following:

  f :: IO ()
  f = IO $ \world -> case putStrLn "foo" of
    IO _ -> case putStrLn "bar" of
      IO g -> g world
prints "bar".
Re:Monads Schmonads: Functional Input Without Tears (PYFL) by goto11 on Monday May 24, 2021 @06:10AM (#27262687)
The JavaScript equivalent would be:

    const io_actions = ["hello", "world"].map(s => () => console.log(s));
    io_actions[1]();
which also prints "world" when the JavaScript runtime evaluates the code.
Re:Monads Schmonads: Functional Input Without Tears (PYFL) by pwm on Monday May 24, 2021 @11:00AM (#27265137)
If your point is that one can implement a Haskell like language in any turing complete programming language then sure, you are correct. GP's point however was that Haskell is purposefully designed to be written and thought about this way from the ground up. Ie. putStrLn "hello" is not a command that is executed verbatim when the runtime gets to its source position. It's an IO action and an IO action is just a value that can be passed around or, by virtue of IO being a Functor, mapped over, etc...

If you say that purity and referential transparency are not only reserved for Haskell then again technically sure, but the point of Haskell is that it makes these concepts the centre of its design. Instead of having to jump through hoops to write code where you can do the above you have to jump through hoops to do the opposite.

Re:Monads Schmonads: Functional Input Without Tears (PYFL) by goto11 on Tuesday May 25, 2021 @04:55AM (#27274528)
My point is just that input/output is not pure in Haskell. I believe it is an unfortunate misconception that obscures what the actual cool properties of Haskell is.

IO functions like putStrLn is curried by default, so you can pass them around without executing them. But this does not affect the purity of executing them. And it is not something special for Haskell, you can pass functions around without executing them in almost any language.

The cool thing about Haskell is that code is pure by default, and it is only due to special-casing by the language (the type of "main" being "IO ()") that you can even have operations with side-effects.

Haskell allows you to have parts of the program guaranteed pure, but the program is a whole is not pure if it does any input/output.

Re:Monads Schmonads: Functional Input Without Tears (PYFL) by przemo_li on Wednesday June 02, 2021 @05:07AM (#27366523)
IO is also pure.

It will not be executed until the very last line of your app.

O_O

No seriously. If you wanted to model IO in say Java. Your whole program would be about constructing values. No I/O what so ever. Only do this then that then get a, then if a is this do x other.....

Whole Java app and I/O would only happen when at the very end you execute run method on that constructed value.

That'd not usual Java. After all in Java code itself can do control flow and I/O. Do why bother with those values. Need I/O on line ten out of 100. Do I/O immediately on line 10.

What I/O on Haskell is is side effect. Explicit side effect.

It's possible to write impure code in Haskell but that is not IO. It's when you use escape hatches that break type system guarantees.

Re:Monads Schmonads: Functional Input Without Tears (PYFL) by Twisol on Monday May 24, 2021 @02:11PM (#27267757)
> But isn't it the case in any programming language that impure operations only have side effects when they are executed?

That's a great question! This framing is indeed universally true, which suggests there's something less useful about one or more of the definitions it relies on. For my money, I'm betting on our definitions of "executed" being different.

What exactly does it mean to execute a program? For most of us practitioners, it means using a program for its intended purpose. I think this is closest to the meaning you're using. But this embodies everything at all about a program, so it is quite coarse grained.

Can we break "execution" into smaller pieces? Yes, at least conceptually. First, we can speak of "reduction": it's what happens when you simplify "1 + 1". Second, we can speak of "interaction": it's what happens when you substitute for "x" in "x + 1".

Reduction is purely internal: the program state evolves purely on the basis of the information it already has. We perform reduction in order to turn the program into a more useful form, much as in algebra we might put a linear expression into slope-intercept form.

Interaction operates explicitly on the exchange of information between two parties: the program and its environment. We perform interaction when we need to make some information known by one party available to the other.

Personally, I take my definition of "side-effect" to mean "requires interaction". For instance, take the (JavaScript) program `(x) => x + 2`. This program cannot be reduced; in order to reduce it further, we need to interact with it by providing an argument. That interaction transforms the program to, say, `((x) => x + 2)(42)`, and now we can reduce down to `44`, which cannot reduce and cannot interact.

Of course, if my program was `((x) => x + 2)(42)` from the beginning, there is no side-effect. At least, not one visible from the outside: the interaction between programs `(x) => x + 2` and `42` has been promoted to a reduction via composition.

This kind of interaction allows us to implement request-response protocols between the program and an environment, so long as we have a runtime to mediate the interaction. But it's also somewhat painful to author programs in this style: we have to return a callback all the way back to the top of the program whenever we want to interact.

If we add interaction primitives to the language itself, as in `prompt("Enter a number:")`, we gain the ability to interact from anywhere in the program, in exchange for the added complexity of a runtime that has to keep track of where in the program the interaction is occurring. This is great! But can we promote the `prompt` interaction to an internal reduction as we did with function application?

Well, in JavaScript, _kind of_. Since most symbols are dynamically looked up, you could overwrite `window.prompt` before running the inner program, and reset it afterward. But this impacts every call to `prompt`, not just the one (out of potentially many) you wanted to intercept. Providing an internal `prompt` interaction becomes a bit fraught; it's not very composable. And in other languages, you couldn't do this at all. (Dynamic lookup is itself a kind of primitive effect system, so you can backdoor a surprising number of things through it.)

Suppose that, instead of adding interaction primitives directly to the language, we stick with the original idea of "a returned top-level function is a request for interaction", but try to dress it up a bit more nicely. We still want to be able to perform interaction deep within the program, but we need some out-of-the-way machinery that propagates that interaction up to the top level for us, and manages remembering how to get back to where we were. In other words, we need to implement the system that was previously in the runtime in our program instead. Only the actual doing of actions is left in the runtime.

Without burying the lede, if you do this you end up in one of a few algebraic systems, one of which is monads, and all of which have the property that you can promote interaction to reduction in a composable fashion. (With monads, you need to define your own monad capturing the interactions you care about, and then write an interpreter for that monad that turns your monad's interactions into IO interactions.) Basically, you can mock out the environment in a particularly clean way.

Monads end up being useful for quite a lot besides managing IO. It's very appealing as a solution that doesn't seem to be special-cased for IO specifically. I think that has a lot to do with how they allow you to in general program against interactions and then promote to reductions. It's harder to do that in JavaScript, since there are so many effectful operations, and while you can promote some of them, you can't promote all of them.

Re:Monads Schmonads: Functional Input Without Tears (PYFL) by Blikkentrekker on Sunday May 23, 2021 @07:02PM (#27259425)
Your code is not an implementation, only a type theoretical description.

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.

Re:Monads Schmonads: Functional Input Without Tears (PYFL) by anderskaseorg on Sunday May 23, 2021 @07:17PM (#27259510)
You can write real code given only the definitions I gave:

    someCode :: IO' ()
    someCode = do
      PutStrLn "What is your name?"
      name <- GetLine
      PutStrLn ("Hello, " ++ name ++ "!")
and you can run any such program, for example by translating it to the “real” IO:

    runIO' :: IO' a -> IO a
    runIO' (Pure a) = pure a
    runIO' (Bind ma f) = runIO' ma >>= runIO' . f
    runIO' (PutStrLn s) = putStrLn s
    runIO' GetLine = getLine

    main :: IO ()
    main = runIO' someCode
or you can imagine an implementation of Haskell where IO is IO' and PutStrLn really is that data constructor and no such translation is necessary.

You might ask, what’s the point of separating it out this way, when obviously you still need to actually perform the effects at some layer? The point is to demonstrate that running code in the IO' monad (and, similarly, the IO monad) does not require “reaching into” the pure functions that define it and violating their purity; you just use them as black-box mathematical functions. All the equational reasoning you can do with pure functions applies equally well to the IO monad.

Re:Monads Schmonads: Functional Input Without Tears (PYFL) by Blikkentrekker on Sunday May 23, 2021 @07:27PM (#27259577)
And then you still define them in terms of the actual primitive functions that are a hack.

This is entirely different, for, say, floating point arithmetic, which one could in theory simulate from the ground up by defining one's own float as a vector of binary states and manually implement floating point arithmetic on it.

> All the equational reasoning you can do with pure functions applies equally well to the IO monad.

Only because these primitive functions receive special treatment from the optimizer which ensures that they are not optimized in the same way and allowed to be executed in indeterminate order. — they are very much magical primitives that cannot be simulated ex nihilō.

Re:Monads Schmonads: Functional Input Without Tears (PYFL) by anderskaseorg on Sunday May 23, 2021 @07:48PM (#27259705)
No. runIO' does not define PutStrLn, it translates PutStrLn; there’s a difference. I can write and compile all the IO' code I want without runIO' ever existing, and it has the semantics it has as a data structure built from pure functions. I can write a pure function that computes which effects would happen for a given IO' action for a given sequence of inputs, and I can evaluate this function within the GHC REPL. None of this receives any special treatment from the optimizer.

    -- action -> input -> (return, remainingInput, output)
    simulateIO' :: IO' a -> [String] -> (a, [String], [String])
    simulateIO' (Pure a) input = (a, input, [])
    simulateIO' (Bind ma f) input = (b, input'', output ++ output')
      where (a, input', output) = simulateIO' ma input
            (b, input'', output') = simulateIO' (f a) input'
    simulateIO' (PutStrLn s) input = ((), input, [s])
    simulateIO' GetLine (line : input) = (line, input, [])

    λ> simulateIO' someCode ["Anders"]
    ((),[],["What is your name?","Hello, Anders!"])
The fact that the real IO receives special treatment from the GHC optimizer is an implementation detail that’s necessary for the correctness of GHC’s optimizations, but assuming GHC was implemented correctly, this has no visible effect on how programs are evaluated. If you actually run them, the resulting effects should agree with the predictions of the pure function above.
Re:Monads Schmonads: Functional Input Without Tears (PYFL) by goto11 on Monday May 24, 2021 @03:51AM (#27261966)
This is beside the point. Haskell have a number of built-in unpure operations like putStrLn. You can use the built-in IO type to execute these unpure operations.

If you define your own type called IO you can't use it to execute unpure operations.