News for hackers. Stuff that matters.
Re:Haskell for Web Developers by Chris_Newton on Friday July 26, 2013 @01:45PM (#6109422)
You might not need a deep understanding of category theory to write useful programs in Haskell, but the downsides of relying on those explicit monads to control state and interactions still show through in practical code.

Here’s an early example from the article:

    import Control.Monad.State

    type Interact a = StateT Int IO a

    repl :: Interact ()
    repl = forever $ do
      val   <- liftIO readLn
      state <- get
      liftIO $ putStr "Total: "
      liftIO $ print (val + state)
      put val

    main = runStateT repl 0
Here’s something with similar behaviour written in Python, an imperative language with a reputation for being easy to read:

    total = 0
    while True:
        total += input()
        print "Total:", total
The difference is striking. The latter is obviously much more concise. Ironically, it also seems clearer about how the state is used, having the initialization, reading and writing of that state all kept together. It’s worth considering that the stateful logic is relatively kind here, too, because there’s only a single value that needs to be maintained via StateT in the Haskell version.

The Python code has the added advantage of actually being correct, assuming that the intended behaviour really is to add up the total of all entered numbers over time as the output suggests.

I think this example is instructive in terms of advancing industrial practice rather than the theoretical state of the art. Haskell demonstrates a lot of nice features that mainstream industrial languages lack today, but as soon as any sort of state or effects enter the picture, it becomes absurdly complicated to describe even simple systems. I would love to have future languages incorporate some of the safety that Haskell offers, but I think to catch on with working programmers they will have to hide away a lot of the state/effect details where they aren’t needed, just as tools like type inference have hidden away their own form of boilerplate. It’s not just about not needing to be an expert on category theory, it’s about not having to be aware of it at all.

Re:Haskell for Web Developers by hiker on Friday July 26, 2013 @01:59PM (#6109519)
The syntax in Haskell for dealing with side effects is tedious/verbose by design. The intention is to push one in writing pure programs since pure functions and compositions are easier to test, verify and reason about.

Good Haskell programs are pure; side effects are usually isolated in a "shell" wrapping the purely functional core of your program that interacts with the world (IO, networking, graphics, etc).

Re:Haskell for Web Developers by tmoertel on Friday July 26, 2013 @03:56PM (#6110193)
> The syntax in Haskell for dealing with side effects is tedious/verbose by design.

I don’t think Haskell’s designers have ever had the goal of making imperative programming more difficult. Simon Peyton Jones himself, as far back as thirteen years ago, wrote that “Haskell is the world’s finest imperative programming language.” [1]

If you want to do imperative programming in Haskell, it’s easy: Just code everything within the IO monad. It looks just like imperative code in most other languages, only you get to use Haskell’s light syntax and advanced runtime (with great concurrency abstractions, modern GC, and lightweight threads), so it is indeed a pretty fine imperative experience.

But Haskell also gives you another option for imperative programming, one that mainstream imperative programming languages do not: the option to provably wall off the small amount of impure logic in your code from all the rest. And once you’ve tried this option for a while, you’ll probably never go back to doing it any other way, at least for non-trivial projects.

Keeping the main bulk of your code pure makes life so much easier that it’s worth paying the small additional cost to wall off the impure bits. Yes, you must centrifuge off the impurities. Yes, you must create a protocol wall to safely communicate with those impurities. And, yes, these costs are real. But they are bounded by a small constant effort factor and applied to only a small portion of your overall code. In exchange for this small cost, you get to keep the rest of your code (most of it) pure and collect the purity dividends for the project’s lifetime. For most non-trivial projects the dividends add up to a huge payoff.

So you can use Haskell as a regular imperative programming language, and it's a pretty good experience. But if you use Haskell as Haskell, you can have an even better experience.

[1] http://research.microsoft.com/en-us/um/people/simonpj/papers...

Re:Haskell for Web Developers by Chris_Newton on Friday July 26, 2013 @02:18PM (#6109625)
The syntax in Haskell for dealing with side effects is tedious/verbose by design.

In the entire history of computer programming, I’m not sure language designers taking that kind of attitude has ever worked.

Good Haskell programs are pure; side effects are usually isolated in a "shell"

The real world is stateful, and many useful programming techniques rely on mutable state. Indeed, programs with no externally observable effect would be rather uninteresting, since by definition they can’t do anything useful!

Please don’t misunderstand my position here. I’m strongly in favour of programming languages providing tools to control that state and avoid unexpected effects (or combinations of effects, or ordering of effects). This would prevent many common classes of programmer error, surely improving the quality of production software significantly.

However, I don’t accept that trying to completely separate the two worlds is necessarily the best way to achieve that benefit. I think adopting the hard line you describe is one of the reasons that functional programming languages haven’t taken off in the industry as a whole, yet several useful tools found in those languages have been widely adopted in recent years.

Re:Haskell for Web Developers by TuringTest on Friday July 26, 2013 @03:03PM (#6109873)
"functional programming languages haven’t taken off in the industry as a whole"

You mean, except for Erlang?

Re:Haskell for Web Developers by davidw on Friday July 26, 2013 @03:28PM (#6110007)
If Erlang is an example of "taken off"...

I am currently using Erlang on a project because it was a good choice, but I would not exactly consider it popular. Popular is stuff like Javascript, Python, Ruby - even Go.

I think it's indicative that in an example of how simple Haskell is supposed to be, you find this several paragraphs in:

> This is an example of a monad transformer, namely the composition of StateT ( State Transformer ) with the IO Monad. The values from the IO monad are lifted into the State monad with the liftM function.

That makes me curious - I'd like to figure out what all that means, exactly, what the concepts are, what they're useful for, and so on.

But I don't know if I'm a "typical web developer" either.

Re:Haskell for Web Developers by TuringTest on Friday July 26, 2013 @05:22PM (#6110681)
Monad transformers is one of the trickiest parts of using monads, and certainly they're not well explained at the example - I'm afraid the linked article does an awful job at introducing monads to web developers, when most of the basic terms used remain without a proper definition.

For what I've learned about transformers (although I haven't used those at practical projects), they are used to combine several monads and wrap them around a single value with several layers of monadic types, so that the adequate monad can handle the inner value when the occasion arises. But don't take my word for that; understanding transformers "does" require knowing a good deal of category theory.

Re:Haskell for Web Developers by dllthomas on Friday July 26, 2013 @09:19PM (#6111458)
Using monad transformers doesn't require any category theory, just Haskell and an understanding of Haskell's use of monads (which are inspired by category theory but aren't going to help you much with proofs). It might help in writing them - I've not written any that weren't toy examples, so I couldn't say.

The idea behind monad transformers is simply that they wrap a monad and give back a monad (which could in principle be wrapped again).

So you can have, for instance,

    StateT Int (ReaderT String IO)
You would have a monad that carries a modifiable integer, an unmodifiable string, and which sequences IO actions.

There is a function called lift which wraps a monadic value in a transformer. So for the above, for the unfamiliar, ReaderT provides

    ask :: ReaderT a m a
which here would be specialized to

    ask :: ReaderT String IO String

If I were working in that monad in do notation, I could do something like:

    str <- ask
and get back the string the reader provides in str. If I were working in our entire stack, though, ask isn't the same type - so I could instead do something like:

    str <- lift ask
to turn a ReaderT String IO String into a StateT Int (ReaderT String IO) String.

So if I had:

    flip runReaderT "foo" $ flip runStateT 7 $ do
        str <- lift ask
        modify (\ x -> x + length str)
        i <- get
        lift $ lift $ putStrLn $ str ++ show i
we could look at the type of the entire do notation expression. It must have a StateT Int on the outside, because the first thing we do with it is runStateT; it must then have a ReaderT String because the next thing is unwrapping a ReaderT. Running through it:

        str <- lift ask
grabs a String ("foo") out of an ask that's been lifted into our stack from a ReaderT String IO String

        modify (\ x -> x + length str)
At the top level, updates the state in our StateT with the result of applying the function to the current value. In this case, 7 + 3 = 10, so the StateT on the outside now holds 10.

        i <- get
grabs that 10 from the StateT and calls it i

        lift $ lift $ putStrLn $ str ++ show i
Appends the string we grabbed ("foo") and the stringification of i ("10"); this is passed to putStrLn which gives us a value of type IO () that, when evaluated, will print "foo10". IO is not the monad we're working in, though, so we lift it into ReaderT and then lift the ReaderT into StateT, to be ultimately unwrapped. The whole expression here has type IO (), and could serve as a definition for main if you want to play around with it.

I should admit that I lied a little bit. The lifts are actually not necessary, because of some typeclass voodoo that I think makes it slightly harder to understand coming in but usually easier to use (unless you need to nest two transformers of the same type...). What's done is that get and ask and such aren't defined just for the one type but for anything that implements MonadState or MonadReader (respectively, as it happens). Then, there is an instance defined for "any monad transformer wrapping anything that implements MonadState", &c, which obviously propagates up the stack, so most of the time you can leave out explicit calls to lift.

Re:Haskell for Web Developers by sseveran on Friday July 26, 2013 @01:56PM (#6109501)
In real life (not contrived examples) haskell greatly simplifies dealing with state. Isolating IO makes it much simpler to reason about where exceptions can come from.
Re:Haskell for Web Developers by Chris_Newton on Friday July 26, 2013 @03:08PM (#6109900)
In real life (not contrived examples) haskell greatly simplifies dealing with state.

That is the assumption I’m questioning.

For example, let’s consider quicksort. Hopefully we can agree that this is a substantial and practically useful algorithm, and one that fundamentally relies on mutable state for its performance and scalability.

I recently posted a link here to a discussion on haskell.org[1] about implementing a real quicksort. This was contrasted with the usual elegant but not-really-quicksort version that has propped up a million functional programming advocacy posts, and with the original C version[2].

Neither Haskell version seems particularly simple to me when compared to the C, and I see little extra safety in return for all the Haskell syntactic overhead that couldn’t have been had just as well with a couple of "const" annotations in numerous imperative languages.

Obviously not every case is as self-contained as this algorithm and in other contexts Haskell’s approach would fare better. But a lot of real world code is stateful, and a lot of it uses this kind of local state, and so I contend that making everything explicit, Haskell-style, does not greatly simplify dealing with state in general.

[1] http://www.haskell.org/haskellwiki/Introduction/Direct_Trans...

[2] http://www.haskell.org/haskellwiki/Introduction#Quicksort_in...

Re:Haskell for Web Developers by sseveran on Friday July 26, 2013 @06:09PM (#6110885)
So for me the real life tends to be much larger applications. I tend to worry less about the efficiency of something like quicksort in haskell. If I need very high performance from something I tend to use C anyhow. This tends to be very small and isolated blocks of numeric code. Otherwise network latencies tend to overwhelm performance speedups.

All that aside if you think about the state of an application globally and don't worry about using state in small areas like quicksort then there are big wins to be had. When building scalable services STM makes it much easier to perform state updates and removes trying to reason about locks. Now this does require a big change in how applications are reasoned about and designed.

So having been involved in many things the world contains too much state. Much of the world could be more stateless. I write a lot less very stateful code than I used to. And the code that I do write tends to be more correct. The ability to easily mutate state is now something that scares me.

Also when used correctly haskell doesn't provide a little safety, it provides a lot of safety.

Re:Haskell for Web Developers by Chris_Newton on Friday July 26, 2013 @07:00PM (#6111042)
I do agree with you on the general principle of not using state arbitrarily. As I see it, this is an example of the still more general principle that code shouldn’t depend on anything without good reason. The more dependencies are involved, the harder it is to maintain or reuse code, to run automated tests against it in isolation or review it formally to check the logic, and so on.

However, where I sometimes have a slightly different view to some functional programming enthusiasts is that I don’t see state as some sort of inherent evil. My interest is in writing code that is correct, maintainable and efficient. Writing pure functions is one possible technique to help reach that goal, but to me it is only a means to an end. In particular, it is only one case of the more general principle that stateful resources and effects acting on them should be specified clearly enough that bad things provably can’t happen, but they don’t need to be emphasized or restricted any more than that, particularly if it means compromising on other areas such as readability.

Re:Haskell for Web Developers by dllthomas on Friday July 26, 2013 @03:18PM (#6109960)
I don't think it was an assumption; I think Steve was speaking from experience. As someone working extensively in C and doing a fair bit of Haskell, I'm finding my C to be more verbose and less safe. The C runs faster, in my application; sometimes I write it faster and other times slower, depending on a bunch of factors.
Re:Haskell for Web Developers by Chris_Newton on Friday July 26, 2013 @03:19PM (#6109963)
That’s fine. I’m just saying that my experience differs, and trying to demonstrate why.
Re:Haskell for Web Developers by nilkn on Friday July 26, 2013 @11:54PM (#6111820)
What experience do you have building large real-world applications in Haskell? I'm just curious.
Re:Haskell for Web Developers by dllthomas on Friday July 26, 2013 @03:29PM (#6110012)
Sure, no worries, word choice just bugged me a bit.
Re:Haskell for Web Developers by Chris_Newton on Friday July 26, 2013 @05:36PM (#6110737)
Then I apologise; I didn’t mean anything by it. I can’t edit the post any more, but please read something like “position I’m challenging” instead.
Re:Haskell for Web Developers by dllthomas on Friday July 26, 2013 @06:30PM (#6110964)
Quite alright.
Re:Haskell for Web Developers by runT1ME on Friday July 26, 2013 @02:01PM (#6109528)
>The Python code has the added advantage of actually being correct, assuming that the intended behaviour really is to add up the total of all entered numbers over time as the output suggests.

Only in a single threaded environment. However, concurrently, the Haskell code stays correct in a concurrent environment while your python code has bugs.

Extrapolate a bit, and think about how many python functions may be slightly less trivial than yours and yet still have the same concurrency issues...

Re:Haskell for Web Developers by Chris_Newton on Friday July 26, 2013 @02:28PM (#6109695)
Contrary to the hype, I think plenty of useful code does still run in a single-threaded environment, so I find your argument unconvincing.

That said, even in an environment with concurrency, I’m not advocating uncontrolled state changes as typified by current imperative programming languages. I’m arguing that we could benefit from the robust theory underlying languages like Haskell, but used more transparently so the developer only has to worry about it when it matters.

For example, you could be running a second thread in parallel with the one we’re looking at here, but if its effects are constrained to replying to a network-supplied request for the current time and reading the system’s clock, it doesn’t matter at all that our interactive adder is running at the same time. These effects affect different, independent resources and will never interact, so there is no benefit to cluttering either code path with extra details.

What I’d really like to see is a language that could understand those resources and how they are affected by each thread in terms of reads and updates. I want it to stop me from modifying the code later so that it accidentally becomes vulnerable to interactions that I’m not fully controlling. I want it to provide me with tools to specify how potential interactions should be handled, in a way that is systematic and robust but otherwise as simple as possible, and that can be applied at whatever level of my design makes the most sense.

Research into type and effect systems is addressing challenges like these, but I’m hoping that when the dust settles, the final version will look a lot more like Python with a few strategically placed annotations than Haskell where these implementation details are in your face all the time (even if most of the time you don’t actually need to worry about them).

Re:Haskell for Web Developers by runT1ME on Friday July 26, 2013 @02:51PM (#6109822)
>I want it to stop me from modifying the code later so that it accidentally becomes vulnerable to interactions that I’m not fully controlling. I want it to provide me with tools to specify how potential interactions should be handled, in a way that is systematic and robust but otherwise as simple as possible, and that can be applied at whatever level of my design makes the most sense.

That's...the state monad. The compiler tells you when you try to access it in a way that is not allowed.

You have to be explicit with sharing.

Re:Haskell for Web Developers by Chris_Newton on Friday July 26, 2013 @03:16PM (#6109943)
That's...the state monad. The compiler tells you when you try to access it in a way that is not allowed.

But the price for that is that I always have to access it in a cumbersome way, even when being so explicit makes no useful difference to the correctness of my code.

You have to be explicit with sharing.

I don’t want to be explicit with sharing.

I want to be explicit with sharing when it matters, and otherwise not to worry about it, safe in the knowledge that the language will warn me if I try to do something later that invalidates any assumptions I’m making now.

Re:Haskell for Web Developers by pekk on Friday July 26, 2013 @04:50PM (#6110494)
If your argument is that it's better to be explicit with sharing, then why would you want to use threads that implicitly share 'total'?
Re:Haskell for Web Developers by millstone on Friday July 26, 2013 @07:44PM (#6111176)
I'm intrigued by the claim that the Haskell code is correct in a concurrent environment. If I run two copies of this function concurrently, won't they step on each others' toes as they fight over the file offset of stdin?
Re:Haskell for Web Developers by dllthomas on Friday July 26, 2013 @02:17PM (#6109623)
You mean the Haskell code stays equally incorrect in a concurrent environment...
Re:Haskell for Web Developers by asdasf on Friday July 26, 2013 @02:31PM (#6109712)
What is incorrect about it?
Re:Haskell for Web Developers by tel on Friday July 26, 2013 @02:38PM (#6109758)
The thread op assumed that the code was supposed to accumulate the amounts ever entered. The Haskell code doesn't accumulate, it adds you input to the prior state, prints that sum, then stores your input, not the sum as the next state.

Of course, that's just a (likely true) assumption of what the behavior was supposed to be and it extrapolates far from the point. The example didn't really intend to show off a particular behavior but instead the interweaving of effects.

Re:Haskell for Web Developers by Chris_Newton on Friday July 26, 2013 @02:53PM (#6109832)
The example didn't really intend to show off a particular behavior but instead the interweaving of effects.

Indeed. My point was not to nitpick an interesting article. I was trying to illustrate how making so many details explicit in Haskell has a real, practical downside: what seems to be an obvious logic error had slipped through, where it surely would have been spotted easily in the simpler Python code. Moreover, no-one had even mentioned this possible bug after a couple of hours and dozens of posts here, though of course that could just be because no-one else felt this point was important enough to make rather than because they hadn’t noticed.

Re:Haskell for Web Developers by dllthomas on Friday July 26, 2013 @03:00PM (#6109860)
FWIW, I tend to prefer using modify rather than set wherever that makes sense, which would make this particular bug harder to express.
Re:Haskell for Web Developers by tel on Friday July 26, 2013 @03:35PM (#6110050)
Yeah. I didn't follow your point since I didn't feel like this was a terrifically idiomatic example. I felt like the bug was equally easy to catch in either expression.
Re:Haskell for Web Developers by nightski on Friday July 26, 2013 @04:35PM (#6110418)
No offense but you failed miserably. If you were trying to reproduce the python code in Haskell, the example is not what you would write. This is a 1 liner in Haskell. The two examples do not represent the same thing.
Re:Haskell for Web Developers by Chris_Newton on Friday July 26, 2013 @05:33PM (#6110727)
The two examples do not represent the same thing.

This is a claim I don’t understand. They are both simple examples of representing an algorithm that maintains state in their respective languages. Of course you could write it as a one-liner using a different style in Haskell, and in various imperative languages for that matter. However, my point was that making these monadic abstractions explicit everywhere in Haskell does add weight to the code. That continues to be true for more complicated stateful code that can’t be rewritten as a one-liner or expressed more elegantly using recursion anyway.

Re:Haskell for Web Developers by nightski on Friday July 26, 2013 @09:04PM (#6111413)
I simply do not agree that the abstractions add weight to the code. If anything I think that they make it more concise. It scales much better than constructs given to you in Python. But don't take my word for it, try writing a complicated Haskell program with lots of effects. I think you will find the capability Haskell provides to compose and abstract a huge boon.
Re:Haskell for Web Developers by Chris_Newton on Friday July 26, 2013 @09:26PM (#6111472)
But don't take my word for it, try writing a complicated Haskell program with lots of effects.

Unfortunately it’s late and I don’t have time to spend the next few weeks writing Haskell code to try your experiment. I’m guessing no-one else reading this does either. Perhaps you could instead direct us all to some existing projects that demonstrate the advantages you’re describing, so we could see the kind of code you’re thinking of and make up our own minds?

Re:Haskell for Web Developers by nightski on Saturday July 27, 2013 @12:57AM (#6111924)
The thing is I could throw a bunch of Haskell at you but in the end it wouldn't really mean anything. When I embarked on learning the language there were many times I almost threw in the towel. It was hard to see beyond the initial frustrations. Haskell code looked confusing, verbose, ugly, and so on. It was only by taking the time of going through this process that I came to an understanding - followed by appreciation.

But I don't claim to be incredibly intelligent. It is very possible you or someone else here could look at a heap of Haskell code and just immediately understand the advantages/disadvantages without having gone through learning all of the "why".

Your time is yours. Don't let me try to tell you what to do with it. Heck you can make a fortune just writing PHP so is there any reason to learn anything else? I'd say anyone who loves their craft would want to at least give all new things a shot and invest some time into learning what is out there.

The project I took on initially to learn Haskell was translating a real time sparse 3D reconstruction computer vision algorithm. It was incredibly daunting and challenging. But in the end very worth it!

Re:Haskell for Web Developers by Chris_Newton on Saturday July 27, 2013 @09:30AM (#6112807)
The thing is I could throw a bunch of Haskell at you but in the end it wouldn't really mean anything.

It is odd that you seem to be assuming I’ve never written anything in Haskell and that the concerns I’ve expressed are based on a sceptical reading of one article. I’m quite sure I’ve never written anything to that effect here.

I make no claim to special expertise or authority. Indeed, I’m almost entirely self-taught, so it’s certainly possible that I have completely missed some key point. However, I’ve been following Haskell’s development for years and written enough small/medium projects in it to have formed my own opinions. My experience has been that for mostly pure code where it’s a natural fit, Haskell has a lot to like, but for more interactive systems, it often does become rather awkward for exactly the reasons we’ve been discussing. (Edit: There’s a good example of this in the article: the chat room using WebSockets.)

In the real world, people do sometimes just dump half of their program into IO to be done with it. In the real world, you do wind up repeating essentially the same logic multiple times to cope with monadic and non-monadic cases (or the authors of libraries you use did, but sometimes you are that author) and at times you do need things like explicit lifts. In the real world, sometimes you do want to be in the same monad twice. In the real world, there are awkward corner cases in the language, and you do wind up relying on GHC extensions to help clean them up. In the real world, people do write elegant code like the popular not-quicksort example despite its dubious performance characteristics.

None of this takes away from the power and usefulness of Haskell’s type system, or neat ideas like STM if concurrency is relevant to your application. But this isn’t some kind of either/or world, where having some good points automatically means a language can’t have any bad ones.

Re:Haskell for Web Developers by asdasf on Friday July 26, 2013 @08:42PM (#6111367)
It is made explicit and verbose in that contrived example because it specifically an example of those things. I am having a really hard time believing that you genuinely don't understand this obvious fact.
Re:Haskell for Web Developers by Chris_Newton on Friday July 26, 2013 @09:22PM (#6111464)
Of course I understand that this is a contrived example.

What I don’t accept — without evidence to the contrary — is that it is unrepresentative. Would more “serious” examples of implementing stateful algorithms using monads and similar tools not be similarly verbose, given the explicit nature of such details in Haskell? Maybe that really is true for experts, in which case I would be happy to learn about it and update my views. Examples are welcome.

For now, I have never personally seen it, and it’s not immediately obvious to me how Haskell code would beat a dedicated imperative language at its own game in terms of conciseness. Correctness guarantees, sure. Performance, maybe, if we reach the point where powerful optimisations are possible in Haskell because of the extra information available. And for conciseness, I’m not suggesting it’s orders of magnitude worse or anything silly like that. But when, by design, your effects and sequencing have to be singled out and specified explicitly every time, you’re starting at a disadvantage compared to systems that incorporate that behaviour implicitly.

Please also see my comments on quicksort elsewhere in this thread.

Re:Haskell for Web Developers by dllthomas on Friday July 26, 2013 @02:41PM (#6109772)
"Total: " implies that it's meant to be summing the input values. It's actually only summing the current and the previous, because it puts back val not (val + state).
Re:Haskell for Web Developers by pekk on Friday July 26, 2013 @04:48PM (#6110488)
Why are you having multiple threads share 'total' at all?
Re:Haskell for Web Developers by stonemetal on Friday July 26, 2013 @04:49PM (#6110489)
Frankly the two aren't equivalent in behavior. So of course the python version is simpler, it does less. The Haskell code equivalent to your python version is almost as trivial.

    repl :: Int -> IO()
    repl state = do
      val <- readLn
      print ("Total: " ++ (show (val + state)))
      repl (val + state)

    main = repl 0
Re:Haskell for Web Developers by Chris_Newton on Friday July 26, 2013 @05:16PM (#6110648)
So of course the python version is simpler, it does less.

What does the Haskell version do that the Python doesn’t? In terms of externally observable behaviour they both prompt for inputs and then add them up. In terms of design they’re both infinite loops that maintain one item of state.

I understand that the example was written to show the State monad, and obviously the same externally observable behaviour could be achieved in other ways in this simple case. My point is that in imperative languages you get that State behaviour for free, and unlike the simplified alternatives to the Haskell that rely on recursion instead, such as the one you posted, the imperative state-for-free model scales up when you start to get lots of state and mutation going on. It doesn’t start to suffer in performance metrics like speed or memory usage, nor does it start to have unpredictable performance characteristics in complex systems.

As I’ve stated elsewhere in this thread, this argument is not meant to belittle Haskell or dismiss the clear advantages its model offers. I’m arguing that there is a price to making those things as explicit as Haskell does, and that price is probably too high for mainstream industrial acceptance, so if we’re going to reap the benefits of the sound foundations on an industry-wide scale, they need to be available more transparently.

Re:Haskell for Web Developers by stonemetal on Sunday July 28, 2013 @11:20PM (#6119169)
As you say the Haskell version explicitly controls state, your python version doesn't. If the python version had access to the variables in question under locks with as much security as the Haskell version then they would be doing the same amount of work. Sure they don't do anything observably different but it is a daft example with no driving motivation for why someone would write code that way.
Re:Haskell for Web Developers by nightski on Saturday July 27, 2013 @01:08AM (#6111950)
The imperative one scales alright, into an un-maintainable nightmare of bugs.

The problem is that the imperative model places the entire burden in the programmers head (even when it may not even be code you wrote!) whereas the Haskell version makes everything explicit.

Re:Haskell for Web Developers by atondwal on Friday July 26, 2013 @04:43PM (#6110454)
His example is intentionally contrived to show a minimal example of StateT. This is who you'd really do it in Haskell:

for strings:

    main = repl ""

    repl :: String -> IO ()
    repl a = getLine >>= \c -> print (a++c) >> repl (a++c)
and it's not that much harder for Ints

    main = repl 0

    repl :: Int -> IO ()
    repl a = fmap read getLine >>= \b -> print (a+b) >> repl (a+b)
or using do notation

    repl a = do $
       b <- getLine 
       print sum
       repl sum
       where   
           sum = a + read b
which is still concise and easy to read.
Re:Haskell for Web Developers by dllthomas on Friday July 26, 2013 @07:03PM (#6111052)
One could also do something like

    getContents >>= mapM_ print . drop 1 . scanl (+) 0 . map read . lines
Re:Haskell for Web Developers by mietek on Friday July 26, 2013 @06:15PM (#6110917)
The `StateT` example in the article is unfortunate, as it reinforces the misguided notion that handling state in Haskell requires complicated machinery, such as monad transformers. This is simply false. You can use a mutable reference, like this:

    import Control.Monad
    import Data.IORef

    main = do
      ref <- newIORef 0
      forever $ do
        val <- readLn
        modifyIORef ref (+ val)
        total <- readIORef ref
        putStrLn ("Total: " ++ show total)
Haskell's libraries haven't been designed to make this use case as concise as possible, but nothing prevents you from introducing more succinct notation. To illustrate this point: In Haskell, the `forever` control flow operator is not a language keyword, but a function you could write yourself. In Python, could you write `print` yourself?
Re:Haskell for Web Developers by eurleif on Friday July 26, 2013 @06:17PM (#6110921)
>In Python, could you write `print` yourself?

In Python 3, where print is a function? Yes.

In Python 2, not with exactly the same syntax, but you could certainly write a function to provide the same features.

Re:Haskell for Web Developers by zeckalpha on Saturday July 27, 2013 @11:36AM (#6113273)
A better example would have been `if`.
Re:Haskell for Web Developers by olenhad on Friday July 26, 2013 @02:55PM (#6109840)
I've been working with clojure, and atleast for me, it offers the freedom to work with both pure and impure code with relative ease, whilst still being conservative on state manipulation.
Re:Haskell for Web Developers by dpratt on Friday July 26, 2013 @01:58PM (#6109512)
I've been coding in Scala for the past couple years, and it is basically exactly what you describe in your last paragraph.
Re:Haskell for Web Developers by Chris_Newton on Friday July 26, 2013 @02:48PM (#6109810)
Scala is one of those frustrating languages for me.

A lot of the basic syntax and concepts are very much as I’d wish to do them myself. For example, I wrote a toy compiler years ago that not only used the var/val distinction but even used exactly the same terminology. I’ve seen a few videos of Martin Odersky, and he’s one of those presenters where I find myself nodding along with almost everything.

Sadly, I think Scala suffers from a similar heritage problem to C++. The good ideas underlying it always seem slightly held back by the historical baggage and compatibility issues, and somehow it never feels quite as clean and tidy as it should. I understand the benefits of building on such well-established foundations, but as with effects in Haskell, sometimes silly things just seem to take far more effort than they should, even though much of the language appeals to me.

Re:Haskell for Web Developers by asdasf on Friday July 26, 2013 @02:31PM (#6109706)
>The Python code has the added advantage of actually being correct, assuming that the intended behaviour really is to add up the total of all entered numbers over time as the output suggests.

What output? I don't understand why you wrote python code that does something different than the haskell example does, and then decided that makes the haskell code wrong.

Re:Haskell for Web Developers by Chris_Newton on Friday July 26, 2013 @02:38PM (#6109754)
I think if you’ve got an example of an open-ended read loop, and it collects numbers, and you’re printing something that says “Total:”, it’s reasonable to ask whether the intent was to print the total of the numbers collected by the loop so far.

That this side discussion has happened almost makes my point for me. If the Haskell code had described what the mutable state actually was (the total to date or the previous entered value) rather than getting hung up on the fact that it was mutable state at all (even as written, the term “state” appears five times in this trivial algorithm) then we wouldn’t be having this conversation.

Re:Haskell for Web Developers by asdasf on Friday July 26, 2013 @02:52PM (#6109824)
>it’s reasonable to ask whether the intent was to print the total of the numbers collected by the loop so far.

Yes, it is reasonable to ask that. But you just said it was incorrect, you didn't ask that.

>That this side discussion has happened almost makes my point for me

I don't see how. Your point appears to be "I can write shorter python". You can write shorter haskell to do that too, the point was to demonstrate the State monad, not to be concise.

Re:Haskell for Web Developers by dllthomas on Friday July 26, 2013 @06:48PM (#6111005)
If the code isn't incorrect, the label printed is. It is not computing the total.