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).
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...
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.
You mean, except for Erlang?
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.
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.
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.
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...
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.
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.
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...
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).
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.
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.
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.
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.
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.
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?
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!
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.
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.
repl :: Int -> IO()
repl state = do
val <- readLn
print ("Total: " ++ (show (val + state)))
repl (val + state)
main = repl 0What 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.
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.
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. getContents >>= mapM_ print . drop 1 . scanl (+) 0 . map read . lines 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?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.
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.
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.
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.
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.
Here’s an early example from the article:
Here’s something with similar behaviour written in Python, an imperative language with a reputation for being easy to read: 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.