128 points · by rwosync · 13y ago · 163 comments
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.
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?
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.
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.
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?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.
The second example from the article uses 8-lines of Haskell, a hand-waving explanation of a state transformer monad, composition, and a state transition diagram to demonstrate how easy it is to write trivial Haskell programs. The program in question takes a number from stdin, adds it to a counter, and prints the result.
"Web developers," being those who have experience building applications using web-based technologies, have a plethora of tools and languages at their disposal that don't require the up-front investment of learning Haskell.
Haskell has a lot to offer but I suspect the only people interested in using Haskell in their web application projects are Haskell developers or people who've been convinced that they will be smarter if they learn Haskell.
Also, the example of the compiled JavaScript from Fay is horribly obfuscated:
return Fay$$_(Fay$$_(
Fay$$cons)(i))(Fay$$_(
Prelude$enumFrom)(
Fay$$_(Fay$$_(
Fay$$add)(i))(1)
));
Oh, God, my eyes. Any idea at all what that does? I can tell you one thing: I would not want to debug that on a Friday night. Or a Tuesday afternoon. Or ever, really.Kind of have to agree with a few of the other commenters here who are saying things along the lines of "You can do anything with a hammer, if a hammer is what you have."
Also: this reminds me of a "LISP for Web Development" talk I went to a few years ago. The speaker was talking to a bunch of web devs about how LISP has an undeserved reputation for being domain specific (academia, astronomy, whatever). He then went on to explain how you could use it for calculating the results of some kind of physics experiment and output it as an HTML table. Uh-huh. My buddy and I walked out after about 25 minutes.
Am I being unfair?
>> As an example of we’ll use JMacro to implement a simple translator for the untyped typed lambda calculus.
Nope.
Do you often debug the assembler output of your compiler? Same thing; fix the Fay code, not the Javascript that the compiler generates.
I'm not sure Fay now generates sourcemaps, and either way not all browsers support them.
So it's pretty much guaranteed you'll have to debug generated javascript at some point.
Without reading the article or having used fay, I actually knew that that was a JS translation of `enumFrom` and that you'd probably left out part of it. An editor color scheme could probably reduce the noise of all the "Fay$$" namespacing (or whatever that is) stuff.
I'm not sure I would call it unfair, but I wouldn't call it reasonable or logical. You don't have to use haskell for your front end development if you don't have someone to do it. You don't have to use haskell for your back end development if you don't have someone to do it. He just showed some of what is available if you do want to do it. Our front end developer knows haskell, and works on the backend as well writing haskell. She still doesn't use clay or fay though, she uses SASS and just plain old javascript.
Also, Fay output isn't obfuscated, it is just accurately translating haskell to javascript, which means lazy evaluation.
I've been looking into this myself and I have a similar background as you (elementary calculus and linear algebra; I also took number theory as part of a math minor). So far it looks like I should pick up a bit of abstract algebra/topology (rings, fields, groups, etc) then I should be able to start off on the shallow end of category theory and work from there. At the same time I need to improve my understanding of how monads, monad transformers, monoids, functors, etc work in Haskell from an operational standpoint; I have a basic understanding now but I'd like to dig deeper.
The thread I linked above has a lot of links to books and stuff like Reddit's r/haskell and other places, that you can sort through to see what works for you. I have yet to make that determination for myself, but there's plenty to choose from. I actually picked up a copy of Benjamin Pierce's "Basic Category Theory for Computer Scientists" a few years ago based on someone's recommendation, way before I got into Haskell, and didn't make the connection until I picked up his book on type theory recently (while researching a paper on FP) and thought his name looked familiar.
Ultimately I'm hoping to be able to get deep into type theory and go through that Homotopy Type Theory book that came out recently.
As for category theory, after reading through that thread [1] and the Reddit thread [2] that it links to, I think Conceptual Mathematics: A First Introduction to Categories [3] will be my first read on category theory (but probably followed by the Rosetta Stone paper). That book receives some strong recommendations as a first book in the Reddit thread [2].
[1] https://news.ycombinator.com/item?id=6041726
[2] http://www.reddit.com/r/haskell/comments/1ht4mf/books_on_cat...
[3] http://www.amazon.com/Conceptual-Mathematics-First-Introduct...
If you enjoy it anyway: I like (http://www.haskell.org/haskellwiki/Typeclassopedia) for how it discusses how the different type classes in Haskell relate. I found this a lot more practical coming from this direction but your taste may vary.
I'd also highly recommend going through Types and Progrmaming Languages by Pierce (http://www.cis.upenn.edu/~bcpierce/tapl/) if you are interested in the area. This gives you a good background on type system stuff.
There are tons more links to category theory stuff here (http://mathoverflow.net/questions/903/resources-for-learning...)
Some people like thinking about category theory when they program but in the end its still just a bunch of (cleverly organized) abstract interfaces.
As for background, I think some familiarity with set theory would be most useful, groups and rings and such a bonus. Calculus won't be of much help. Linear algebra might, depending.
of course, that doesn't have much to do with haskell, but if you have an interest in abstract algebra beyond its applicability in haskell, you're in luck, because it doesn't seem to require much background. all it needs is for your head asplode.
caveat: i've tried to learn category theory, and found that i could barely follow a proof, let alone write one. so i picked up a book: http://www.pearsonhighered.com/educator/product/Mathematical...
and i'm working through it now. i could come back to category theory and find that i'm still lost, but i don't think so.
i haven't really had much trouble writing haskell without a decent math background.
Your implication is that "jump in the deep end" means learn category theory. That is entirely unnecessary. If you are interested in category theory, by all means go for it. But don't think it is in any way a haskell requirement.
Looking forward to having 5+ years of experience in this brilliant language.
foo :: M a p f b c => (a -> p) -> b -> c -> a foo f b c = ...
would look something like
A foo<M<a>,p,f,b,c>(AP f, B b, C c) { ...
in Java (I don't know Java, but I hope you gen an idea). I mean, this is a really complex example you've shown. And most of the times, you can (just like everywhere else) write simple type synonyms to express what you want.
For example, what does the M in forM_ stand for? Monad? Something else? What about liftM? Why is it called lifting? Is the M here the same as the M in forM_?
These are just a few examples from this tutorial, but I find that this is pretty much common everywhere in the Haskell world, making it hard to parse semantic meaning from function names if you aren't already immersed in the language and community and well versed in the lingo.
One of the best things I've learned to break out of this is to search for JavaScript implementations of many Haskell concepts when such a concept is doable in JavaScript. It usually leads me to enough understanding of what some function is trying to accomplish to proceed with whatever Haskell tutorial I happen to be reading.
The functions in this library use the following naming conventions:
> A postfix 'M' always stands for a function in the Kleisli category: The monad type constructor m is added to function results (modulo currying) and nowhere else. So, for example,
filter :: (a -> Bool) -> [a] -> [a]
filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a]
> A postfix '_' changes the result type from (m a) to (m ()). Thus, for example: sequence :: Monad m => [m a] -> m [a]
sequence_ :: Monad m => [m a] -> m ()
> A prefix 'm' generalizes an existing function to a monadic form. Thus, for example: sum :: Num a => [a] -> a
msum :: MonadPlus m => [m a] -> m a
http://www.haskell.org/ghc/docs/latest/html/libraries/base/C...Personally, the things that I found hard were idioms (like learning that $ is just avoiding parenthesis, "go" is for loops, etc) and how theres a lot of libraries that make the code shorter at the expense of forcing you to be aware of them (for example, applicatives <$> <*> look alien until you learn what they are and monad transformers add a lot of "magic" to the code as well as force you to use annoying lifts all over the place)
http://blog.ezyang.com/2011/11/how-to-read-haskell/
http://www.haskell.org/haskellwiki/How_to_read_Haskell#What_...
The real question is why use Haskell instead of something else that most people generally consider targeted at the web?
An equally "real" question is why people think "the web" is special in such a way that it requires a different programming language for back-end applications than other server applications use.
There are many programs that run on servers, grinding away on deep questions for extended periods with no more than the bare minimum of communication with the rest of the universe---maybe just a terse "42" at the end of a long run.
But the Web is about talking to users thousands of times per second, sending it all in a hurricane of streams to a database, fetching data for each of them from various databases, streaming it out to a third-party credit card processor, sending the results back to the users....
Haskell's ideal of minimal I/O isolated in a ghetto so the "real" work of the program can remain unpolluted doesn't seem an ideal match for the case where the real work is almost entirely about routing I/O streams.
That's true in the trivial sense, in the same way that "the desktop" is about i/o, or "the command line" is, in that all of those specify an i/o channel.
But web apps or services aren't all about i/o any more than any other applications/services, they just differ in that the main user-facing i/o channel is HTTP.
> Haskell's ideal of minimal I/O isolated in a ghetto so the "real" work of the program can remain unpolluted doesn't seem an ideal match for the case where the real work is almost entirely about routing I/O streams.
Monads aren't ghettos isolated from the real work of the program. Monads are tools for doing the real work of the program -- whether its i/o, or dealing with mutable state in a transactional, concurrency-safe manner, or, well, lots of other things.
Haskell does not avoid IO because it's an unfortunate aspect, it avoids IO to simplify things, to minimize the surface that can break, to make it more easily optimizable to a compiler. "Pollution" is just an emotional term used in teaching beginners to emphasize usefulness and beauty of pure functions.
That isn't what haskell does though, that is the "I've never bothered to learn haskell and want to spread FUD" version of it. I/O is not "a ghetto" in haskell, it is first class. Haskell just makes I/O explicit, it doesn't make it unpleasant. My app is literally nothing but I/O, just plumbing between postgresql and browsers. Haskell has done nothing to make that difficult or unpleasant, and has done much to make it easier and simpler, especially in regards to error handling and form processing, which frankly is most of the code.
1. Built-in concurrency makes your backend scale better.
2. Type system reduces bugs in your code.
3. Mature libraries for web development: frameworks, templating languages, ORMs.
I'll admit there are some downsides:
1. Harder to hire devs that know Haskell.
2. Smaller community.
But it seems like those are getting resolved quickly. The Haskell community is growing, and there is better documentation and support thanks to companies like FPComplete. O'Reilly has been publishing a bunch of books in Haskell, the Stack Overflow community is active and helpful...
Does that mean that if my website becomes "high-profile" next month haskell will have suddenly become a better language than it is now, without the language changing at all?
That applies to any language. Why use perl? Why use PHP? Why use ruby? Why use java? Web development isn't magical, it is just ordinary, general purpose programming. So people use ordinary, general purpose programming languages. Like perl, PHP, ruby, java, and haskell.
No.
> Will I need a graduate degree in category theory to parse the next paragraph in this article?
Oh. Um wait, define web developer for me again?
* Types, types, types. You're probably sick of hearing about Haskell's type system, but it's amazing. Gives you almost all the flexibility of a language like Ruby, PLUS you can encode a lot of your assumptions in types...so if there's a bug you'll catch it at compile time. I like how I can just write a LOT of Haskell code without testing it, and then just compile my project and find all the issues I need to fix. It makes prototyping really easy and fast.
* Awesome abstractions. Functors, monads, first class functions: you know how java is verbose and you end up writing the same boilerplate over and over? Haskell is the opposite.
* Awesome syntax. I really love Haskell's syntax: super clean, and you can modify it however you like. I like writing very readable code (you read code way more often than you write it) and Haskell lets me write very readable code.
* Neat libraries! All that stuff other languages are trying to work around? Like concurrency, or sandboxing? Part of the standard library already. I had written this post a while back (http://adit.io/posts/2012-03-10-building_a_concurrent_web_sc...) that shows exactly how easy it is.
Seriously, if you're curious about languages at all, give Haskell a try.
Purity is great not because you make fewer errors but because when writing pure code you can focus on what needs to happen instead of worrying about state/effects/control flow. While having to sprinkle `liftIO`s around your imperative code sounds dreadful, it's quickly appreciated as a statically checked marker for "code that you need to think harder about".
So what you end up with is a fantastic playground to use mental tools unavailable in other languages due to the complexity overhead. You also have a suite of abstractions that "almost never break" due to their invariants being encoded into the type system and thus checked every single time you reload the file.
People often compare this effect to having a large suite of automatically generated test specs run on every compile. It's like that, yeah, but humans can write tests this bulletproof and no suite runs this quickly.
I get jitters writing Ruby sometimes now because I know I'm fallible and I have to store so much more in my mind in order to reason about it.
Are there any large opensource haskell web apps that one could read to see how it really done ?
[1] http://johnmacfarlane.net/pandoc/
object [ "foo" .= object [ "bar" .= [ "Yum", "Waffles!"] ] ]
Which will give you {"foo": {"bar": ["Yum", "Waffles!"]}}.
You can do traversals when decoding too:
tasty :: JSON -> Parser [String] tasty json = json .: "foo" >>= (.: "bar")
You can also do similar things with lens-aeson:
tasty json = json & key "foo" . key "bar" . _Array
Though I'm less familiar with that, and you won't be inside the Parser monad.
For example, rather than having an Invoice with a status field of Text or String, I have a type InvoiceStatus = Paid | Unpaid | Void. From there, you can write a very precise parser that takes exactly what you want and nothing else. When I apply this approach to each component of the thing I need to parse (or do it generically even), I don't really find myself having to munge javascript types into my data structures.
That said, aeson support for nullary types (i.e. types that hold no "extra" values, like InvoiceStatus above) is trivial and the types make a huge difference in the rest of your code.
So, complex nested structures are a matter of defining Show and Generic instances for any types that don't already have them. From there you can trivially make those types aeson-compatible. Since so many common types are already supported, adding support for your own nested types isn't too difficult. The example use automatic derivation of Generic instances, which may result in some performance problems but is the easiest way to get off the ground.