177 points · by a0 · 11y ago · 137 comments
> Yoneda-crazy: I know Haskell, I know some category theory, but I am highly sceptical that teaching the Yoneda Lemma to C++ programmers is actually useful in any way.
This is infuriatingly true. Everything you do in Haskell you can understand in terms of what code gets executed where and how. This is just as true of Haskell as it is of any other high-level language.
Indeed, you can take an arbitrary Haskell program, and rewrite it in C with the same semantics, and all you'll learn is how GHC's runtime is implemented and how it executes your program. For a small concise program, this actually makes for a nice exercise. I don't know why, but people sometimes seem to think the runtime is "magic".
A side comment, this one's more about CT itself, is that the standard texts don't seem to really have many results. Not compared to, say, any undergrad book on algebra or number theory, where cool theorems come at you every few pages to twist up your brain. Category Theory always felt almost mechanical to me. Lots of definitions and rules for assembling diagrams and such, but then what. Just the Yoneda Lemma and that's it? If anyone can point me to the fun CT theorems, I'd love to hear about them.
Oh man. If you like math, CT gives nice mathematical definitions for stuff. I would love to use my algebra skills to do general programming like I can use my linear algebra knowledge in numerical programming.
I'm making bold claim that I hope someone can debunk with awesome counterexamples:
"CT HAS ZERO APPLICABILITY IN PROGRAMMING"
Using CT to Linear algebra analogy: CT in programming is like learning definitions of vector spaces, subspaces, span, and basis and stopping there. No CT equivalent for solving linear systems, linear transformations, least-squares or eigenvalues. Just because you have rooted programming in cool algebraic notation does not mean anything in itself.
The epiphany I had from this is that, while linear algebra's utility comes in the form of designing efficient algorithms, CT's utility (in Haskell) comes in the form of understanding structures. It's similar to thinking of modular arithmetic in terms of remainders vs. quotient groups. I get lost doing anything complex with the former way of thinking, but when I switch to thinking in terms of basic abstract algebra suddenly the foliage clears and the way ahead is clear.
Category theory is a language created to communicate complex models. If it's not obvious yet that you can't use CT the same way you use algebra, let me state so: you can't. CT must be less powerful than algebra, because you can't reason about complex stuff as easily as you can reason about simple stuff.
Yet, one mostly can not write a program nowadays without using CT. There's no language that does not implement a subset of it. You don't notice it for the same reason that fish do not notice the water.
But as powerless as CT must be, it gives you plenty of tools for simplifying your models, and not having those tools available can only make your program more complex, never simpler.
Another trick Haskell uses is preferring abstractions that are based on concepts from CT[2], and validating the utility of those abstractions on their "rigorous mathematical foundations". This is again just another case of taking you to the math rather than the other way around. Programming languages are first and foremost human languages, meant to be written and read by humans. As such, their power is drawn from a single source: their interaction with human cognition. Whether an abstraction is "mathematical" (whatever that means) has absolutely no relevance to its power, which comes from cognition (and psychology in general) rather than math. All this "in your face" math does is make the machine's job of verifying your software easier.
A Haskeller tried convincing me that such a language is a good fit for human programmers, too, because all it is is a subset of more traditional, impure languages. But the notion of subset => simpler is a mathematical notion with no relevance to cognition. If humans operated in this way, natural languages would have been much more mathematically simpler, too.
[1]: See KeY: http://www.key-project.org/
[2]: To be fair, I'm not sure that Haskell, given its original design philosophy, has much choice in the matter.
Category Theory is more about getting (as one of my professors put it) "a God's-eye view of mathematics". What I have found to be the most deep and useful is the way it provides concrete definitions which unite constructions that mathematicians were already calling the same thing (e.g. products, co-products). It is also absolutely amazing at showing links between different (seemingly unrelated) parts of mathematics. In this way, it forms a sort of lingua-franca for mathematics. This math StackExchange answer[1] gives some really good concrete examples.
If you want a book which gives a lot of more concrete results along with category theory, you should try Algebra: Chapter 0. It is more focused on abstract algebra, but it does it all from a categorical perspective while not assuming you know one iota of category theory (at the start).
[1]: http://math.stackexchange.com/questions/312605/what-is-categ...
On the other hand, CT was invented to talk about homology, so if you want to see a ton of examples of CT being used "in its natural habitat" then look there.
I think anyone who really understands what they're talking about (which is, admittedly, not everyone who talks, sometimes loudly) would happily agree with you and then wonder what we were arguing about :)
Haskell tries to take the line that the "compilation semantics" are second class citizens to the "equational semantics". A lot of the technology Haskell introduces is in some way or another directly aimed at this. It doesn't, however, mean that the compilation (or operational, though that word gets abused and won't take you where you want to go exactly if you google it) semantics isn't totally valid, interesting in it's own right, and a useful thing to study.
Some of the core-er Haskellers like to write about this stuff too. I particularly love Edward Yang's posts on the Haskell Heap
http://blog.ezyang.com/2011/04/the-haskell-heap/
But all that said, the reason for having the compilation semantics take a back seat is not because it's unimportant but instead because if you don't intentionally take that stance then it, due to its front-and-center role in executing your language, will become dominant.What we really want is a language with many compatible and well-developed choices of semantics! Then we can pick and choose our reasoning tools on the fly and know that we won't be led astray by small (or vast) incompatibilities.
It turns out this is tremendously difficult.
It's also important to note that Haskell only does a so-so job at it. Interestingly, this makes it one of the absolute best examples of any large language pulling it off. SML probably takes the cake depending on what flavos you're interested in, though.
Apparently somewhere in the last 20 years people stopped learned about how compilers work.
That knowledge is now kept by the few druids that possess the abilities to read the old runes and release the enchantments that reside in them.
It seems to me that one of the goals of a compiler course is to fill the mysterious gap between what machines do and what high-level languages do. For maximum educational effect, the language being compiled should be the same as the language used for the compiler. Anything higher level than C would probably require a runtime, with garbage collection etc., so a C-like language seems like the obvious sweet spot.
My university (FCT/UNL) had a strong focus in language design, data structures and systems programming back in the 90's as part of the compulsory lectures, with everything else being optional credits.
I think getting lost in the implementation details is what gets many Haskell learners, because the majority know an imperative language and use it as the base.
Law number 3.
What I dislike the most is that the Haskell execution order in particular isn't hard to reason about[+]. Yet, because it's things don't simply happen in the order you write them, people tell beginners to not think about execution order at all, and wait until laziness bite them.
[+] Really. If you just assume that the only things that gets evaluated is the first argument of the IO monad (>>) operator (not (>>=)), and it pulls evaluation until it gets all the data it needs, you'll have 99.9% of the model done. Read about GHC green threads and the FFI and you'll get everything that does not use unsafePerformIO right.
"FP communities: like debating which brand of natural spring water to give millions of thirsty people in the desert"
https://twitter.com/jordwalke/status/566719390272335872
Note that I do genuinely appreciate the discussion, while finding the overall scene humorous.
Case in point: I've probably done more to evangelize functional programming by just demonstrating to colleagues that they too can write their own higher-order functions - just like LINQ! - in C# than an army of Haskellers could accomplish in a lifetime of hurling jargon from category theory. My thought is, if FP is really so great then I should be able to show people by writing some functional code and then having someone else come along later and go, "Hey, that's great!" When I find I can't do that then that's a signal that it's time to double-check the ingredients of my fruit-flavored beverage.
Yeah, that does mean I have to accept that Racket will forever be a hobby language for me. My boring sellout Herman Miller-cradled enterprise developer butt is comfortable with that.
I don't know about that. Sometimes people must make the effort to move beyond their comfort zones in order to find tools that are (potentially) more useful. You cannot expect every improvement to be self-evident with minimal effort. There are significant rewards in "making the jump", so to speak.
...who all claim that they're not thirsty and prefer beer :-)
To quote Bob Harper: As a consequence, using type classes is, in Greg Morrisett’s term, like steering the Queen Mary: you have to get this hulking mass pointed in the right direction so that the inference mechanism resolves things the way you want it to. [https://existentialtype.wordpress.com/2011/04/16/modules-mat...] (I think this applies most of all if one is using type classes to emulate a module system. For other purposes, type classes are quite nice.)
Maybe Backpack will solve these issues. [http://plv.mpi-sws.org/backpack/]
Here's another recent one going in the opposite direction, like this one, but asking Clojure fans about Haskell: https://www.reddit.com/r/Clojure/comments/3h4qdk/what_are_cl...
A lot of the Clojure programmers seemed to focus on things, like records, that often bug Haskellers, too.
[1] http://stackoverflow.com/questions/23727768/which-parts-of-r...
With that, "aeson" for JSON, "sqlite-simple" for persistence and perhaps something like "lucid" for HTML, you are half-way to that twitter clone... :)
The main advantage for me is in code reuse and refactoring, something that really shines for medium-to-large projects, and is unfortunately hard to showcase in tutorial style.
Getting started wasn’t easy, but as you imply, not really due to the language—mainly because the learning materials didn’t suit me. I couldn’t bring myself to finish Learn You a Haskell or any other tutorial, so I just used the language to build stuff and figured things out.
Been thinking about writing a book about my experiences, but it’s Yet Another Project I’ll have to make the time for…
char* response(messy* message) {
body* b = message->body;
if(b==NULL) {
return NULL;}
char** lines = b->text;
if(t==NULL) {
return NULL;
}
if(b->line_count < 11) {
return NULL;
}
return t[10];
}
Writing all of those if statements grows tedious. A lazier programmer could just drop them, but then the program would crash whenever the program received malformed data.With Hackell, though, I can refactor out the if statements and get the following equivalent code:
response :: Messy -> Maybe String
response message = do
b <- body message
lines <- text body
lines `atMay` 10
I want to be clear on a couple of points. First, the Haskell code performs all of the same "null" and bounds checks that the C code made, so this is an apples-to-apples comparison. Furthermore, this isn't using exceptions, like a similar piece of C++ code might try. There's no stack unwinding and nothing can escape to contaminate the rest of your program. Finally, this isn't just a weird special case built into the language. With a minimal amount of effort, I could have each failure return a unique error Code. errorCode :: Maybe a -> b -> Either b a
errorCode (Just value) _ = Right value
errorCode Nothing code = Left code
response :: Messy -> Either Int String
response message = do
b <- body message `errorCode` 1
lines <- text body `errorCode` 2
(lines `atMay` 10) `errorCode` 3
I don't know a way of doing that in any of the C style languages. In those languages, you're forced to add in another if statement every time your code touches message->body to ensure that you're not going to segfault. With Haskell, I can refactor away those if statements and I don't have that code being duplicated all throughout my project.EDIT: improved readability of errorCode
The compiler won't let you generate an executable if you missed a code location.
Whereas in dynamic languages you never know if you have covered all the code locations.
For me, using yesod has been quite a revelation. All of the errors in db operations get caught during my cabal build. This link https://github.com/yesodweb/yesod/wiki/ghci is something i used to test my db code all within the repl cycle after setting some pg env variables. All in all, its way smoother than many other environments i have worked with.
How about a URL shortener instead of a Twitter clone?
https://github.com/ryantrinkle/memoise
Video here: https://vimeo.com/59109358
Pandoc (http://pandoc.org/) is written in Haskell and its modular design makes it easy to peruse without understanding everything.
Haskell shines the brightest when refactoring a moderately sized project (I have been yearning for this, working in a smallish Python codebase), but nothing prevents using it for small things.
{-# LANGUAGE PatternSynonyms, ViewPatterns #-}
pattern Even <- ((`mod` 2) -> 0)
pattern Odd <- ((`mod` 2) -> 1)
testNumber x = show x ++
case x of
Even -> " is even"
Odd -> " is odd"
data Color = Color { r :: Int, g :: Int, b :: Int }
pattern RGB r g b = Color r g b
-- NB: this is bidirectional automatically
printRGB :: Color -> IO ()
printRGB (RGB r g b) = print $ "Red: " ++ show r ++ " Green: " ++ show g ++ " Blue: " ++ show b
-- pretend we have functions to and from RGB and HSV representation
toHSV :: Color -> (Int, Int, Int)
toHSV = undefined -- implement this yourself!
fromHSV :: Int -> Int -> Int -> Color
fromHSV = undefined
pattern HSV h' s' v' <- (toHSV -> (h', s', v'))
-- here we explicitly provide an inversion
where HSV = fromHSV
printHSV :: Color -> IO ()
printHSV (HSV h s v) = print $ "Hue: " ++ show h ++ " Saturation: " ++ show s ++ " Value: " ++ show v
-- demonstrating being able to use pattern
-- to construct a value
addHue :: Int -> Color -> Color
addHue n (HSV h s v) = HSV (h + n) s vThis is just gold!
All the Haskellers I have met seem to be quite normal, helpful. Maybe this guy rubs them up the wrong way.
- A Haskeller once said Haskell is just as easy as Go to learn. I mean, yeah, many moderately complex languages might be as complex as Haskell, but seriously, Go? It is designed to be as simple as possible. Hell, it even doesn't have generics, which is considered pretty essential in nowadays' statically typed languages. And this claim isn't an outcome of ignorance. He is the author of a very popular Haskell learning material.
- Another said: "Steep learning curve is an interesting expression, because what it actually means is that one is learning quickly." Ok, that's not my interpretation of "steep learning curve" of Haskell.
- "The average Java programmers are worse than the average Haskell programmers" thing. This sentiment even existed in one of the "how to spread Haskell to the industry" presentation. I'm pretty sure if Haskell does be accepted by the industry, it will have the exactly same dumb programmers using it. So, what's the point?
You must be lucky if you haven't met any of them in the Haskell community. Actually, their reputation outside of the community is quite terrible. This must be resolved if Haskell wants to succeed. (And yeah, please stop saying "avoid success at all cost". I know it can be interpreted as "avoid $ success at all cost", just stop it.)
I think this is quite relevant.
https://gist.github.com/quchen/5280339
All communities of significant size will have good and bad apples. The Haskell community is no exception. But in my experience most of the community are fantastically patient and helpful people.
My suspicion is this: There are lots of ways to make people feel inferior, or at least make them feel like you think they're superior. Most of them are ones that people probably don't do on purpose. But when you do it, the person you do it to is going to think you're a smug jerk nonetheless. There are also a lot of people who are supremely self-confident and therefore largely immune to being made to feel inferior. Many of them have been like this all their lives, and are therefore oblivious to this social subtlety.
One easy social gaffe that doesn't get discussed much is having no sense of humility about your language's obtuse syntax. Yes, I know, it's a familiarity issue, all languages have obtuse syntax, etc. etc. Doesn't matter. What matters is, if your language's syntax is different enough from Java's or Pascal's then it's going to be widely perceived as being obtuse. And responding to that with anything along the lines of, "Huh, makes perfect sense to me," risks coming across as a smug jerk.
Using the M-word is another famously risky behavior. Ironically, at least in my experience using it is also actively harmful to any attempts to explain the underlying concept, because at this point that word is @$#@ loaded. You can take someone who is already implicitly comfortable with the concept and uses them all the time in practice, and reduce them to a confused heap just by mentioning the M-word. And at that point, any attempt to pursue your goals will also risk coming across as a smug jerk. No, trying to address this issue head-on by writing blog posts with titles like "You already understand. . ." does not help. It just makes you come across as a condescending smug jerk.
That is technically correct in the original meaning of "learning curve".
Many technically inclined people totally disregard changes of language and cling to their perceived "pure" meaning.
But every language community has its toxic elements.
That's a property of all niche languages. Yes, if they get mainstream, they'll lose it, but until then it makes for an easy way to bias in a good way the set of people you could hire for a position.
If we assume companies do not filter well their hires, or that filtering them is costly (a huge "if"), it becomes a competitive advantage. And, as most competitive advantages, if enough people use it, it goes away.
This is actually what the rest of the world says about the tech industry.
(Yeah, I just finished pushing a commit or two in Haskell to my github. And I hang out with Ed Kmett once a month. Oy.)
This is the same kind of weak response you see from Rubyists whenever someone points out their community's well-documented asshole problem (eg: Steve Klabnik bringing a woman to tears by publicly ridiculing her project and offering only an insincere non-apology when called on it, any blog post ever by DHH or ZS, Felipe Contreras' tantrums on public mailing lists):
"Well, in my experience, everyone in my community is super nice and helpful, so you must be wrong."
Off the top of my head, I can easily recall several Haskellers on HN who've come across to me in the past as pricks, and on multiple occasion at that: dons, loup-vaillant, and coolsunglasses.
The Haskell community, like that of Ruby, is quickly getting the reputation it deserves.
I've experienced some cases where I've been spoken to a bit sharply, and some where people have come across a bit impatient when I haven't "got" something they understand. The thing is that I don't process it as people coming across as a dick, so my subjective experience is that the community is helpful. As to the three examples [1] you picked out of Haskellers coming across as pricks, I honestly, truely, completely don't see anything in any of these comments beyond forthright assertions of opinion. Would you be able to maybe break down what you find objectionable?
[1] As disclosure: I currently work with dons, and I also know willtim.
If you don't understand what's offensive about condescendingly spewing falsehoods like "if it compiles, it works" or saying that you can't respect a CS department that uses Python for its introductory CS courses instead of Haskell (and thus doesn't expect its freshmen to know what a Kleisli category is), you've obviously drank too much of the Haskell Kool-Aid to maintain objectivity.
By the same token, you could describe the community of Haskell as witty and friendly by taking SPJ as an example. In my experience, the Haskell community is fairly free of vitriol and of the drama which is fairly common in open-source communities.
This thread reminds me of Tortuous Convolvulus.