by leccine · 12y ago · 0 comments
The difficulty one might find comprehending Haskell is probably because of the semantics rather than syntax - particularly if you have a background in languages like C++ and Java - the first thing you'll be attempting to do is find parallels between this new obscure syntax and what you already know - but they don't necessarily fit, because the language is fundamentally different.
A common example of misunderstanding for beginners is function signatures - in Haskell, one simply defines a function name, followed by two colons, followed by a type declaration which states the function's type. It's as simple as
add :: Int -> Int -> Int
If you're attempting to draw the parallel to the equivalent in another language such as C#, you might think this is the same as int Add(int a, int b) {
...
}
While pretty close, the Haskell equivalent of that is really a coupled argument. add :: (Int, Int) -> Int
The C# equivalent of the original is closer to this Func<int, Func<int, int>> add = a => (b => ...);
At this point it should become a bit more obvious why that "cryptic" function signature is the way it is - it's because all functions in Haskell are secretly single argument functions, and additional arrows indicate that the return type is another function. In other words, the arrow, -> associates to the right, which makes it unnecessary to parenthesize the returned functions - but you can optionally write them for clarity: add :: Int -> (Int -> Int)
As a result, you can partially apply add with a single value, e.g. `add 5`, and a valid function which adds 5 to its argument is returned, e.g. `(add 5) 6 == 11`, and because function application (denoted by a space) associates to the left, you can omit the parens and simply say `add 5 6`.Given that you have some Erlang background, the syntax for implementing functions should not be foreign to you, because they're quite similar, except perhaps "do-notation", which will won't be very intuitive until you grok monads.
For example, this is the default implementation of foldr, in the Traversable typeclass, in terms of a foldMap implementation:
foldr :: (a -> b -> b) -> b -> t a -> b
foldr f z t = appEndo (foldMap (Endo . f) t) z
This does not take long to grok in Haskell, but translating it to any imperative language would make no sense. It requires an understanding of the semantics of Monoids, currying, function application, and Endofunctors. None of these are hard, but none of them exist in more mainstream imperative languages.But heck, this is at least something like what it is doing:
#!python3
from functools import partial
def foldr(f, z, t):
for endo in (partial(f, i) for i in t):
z = endo(z)
return z
Only, um, not quite, because iterables are not exactly foldables, it lacks the generality of actually calling the foldMap function (which can be different in different types), it has no type signatures so it is less strict about its parameter, and this is cheating a bit because python already has nice functional programming tooling compared to many other languages, and so on. But the jist is there, and even some of the performance qualities of lazyness if you get how iterators work in python.I personally suggest you just learn it from scratch. Its not just a different skin over the same ideas, like so many other languages.
(I know this is just a short demo rather than production code, but all the "good examples of haskell" I saw at university were like that too, and much of the online documentation I saw :/ )
Then you should go ahead and start. The syntax is pretty thin. It's not what you're used to, but it's thin.
It's hard to describe what Haskell would be good for without sounding overenthusiastic, so I'll confine myself to saying that Haskell will expand your brain in ways that few other languages will. That said, Clojure is potentially one of those few other languages (depends on your personal development history, though IMHO enough stuff has been stolen from Lisp over the years that it's less of a mind-blow than it used to be), and you ought to learn about modern concurrency from at least one of Haskell, Go, Erlang, or Clojure (or possible Scala via Akka). Haskell opens you to the most correctly-implemented modern concurrency paradigms at once but any of those will get you most of the experience you need.
When one is fluent in Haskell I think the language naturally tends to drive you towards well-factored, reusable designs that can handle change well. I say "fluent" because I don't think one needs to be "expert" to get to this level, but certainly there's a level of experience required to be here. Beginners and pre-fluency intermediates in the language produce god-awful messes of code. (I know, because I have! Fortunately I had the foresight to do that to throwaway personal projects, rather than critical business projects.) I think a great deal of the Haskell propaganda is justified, but beware the Haskell enthusiast who recites the propaganda, but can't clearly explain in their own words the mechanisms that Haskell uses to accomplish it.
Actually, scratch Haskell out of that. Beware any tech enthusiast who can't give a coherent explanation in their own words of why the tech stack has the claimed effects, but just repeats the propaganda again.
First, is it Haskell that drives you toward well-factored, reusable designs? Or is it functional programming? (I know, you can't do Haskell without functional programming. You can do functional programming without Haskell, though. Can you separate the two, and say which one is driving you here?)
Second, have you ever seen Haskell deployed in a large, long-lived production code base? How large? How long-lived? How did it work? (I ask because I remember reading an article on Lisp, which said that X in Lisp is just like Y in an object-oriented language, "with the proviso that in Lisp, all the types exist in the programmer's head". I'm pretty sure that won't work very well on a million-line code base that lives for 30 years. Haskell has a very solid type system, so it won't run into that particular problem but... does it have a track record for large-scale work out in the real world?)
As to where Haskell fits: you're correct, there are many other great languages out there. But I think Haskell is really unique in offering what it does. Clojure, Go, and Erlang are all great in their own regard, but none of them provides the degree of safety that Haskell does. For example, none of them enforce purity, and all three of them freely allow the use of `null` values (which is really quite surprising considering how many problems nulls cause). Clojure and Erlang avoid mutable state like Haskell does (though not to the same degree of rigor) but don't provide the elegant solutions for simulating mutable state that Haskell does with its monads, which almost allow you to "have your cake and eat it too" with state. None of them encourage the degree of abstraction that you'll find in Haskell. Also, at least according to the Computer Benchmark game, Haskell beats all three of them in terms of speed, as well. Haskell's "place" is in generating highly robust code with good performance, and also works as a beautiful language for expressing certain mathematical concepts.
This doesn't make Haskell a perfect language, but it absolutely has a lot to offer that other languages don't. And it's so much different than other languages, that at the very least it can change your perspective on a lot of things.
Of course you can tweak things to be fast in hakell, but to be able to actually program haskell in such a way to, beat other languages in performance, is not a trivial skill.
There are numerous stackoverflow and r/haskell posts "Why is my haskell code 10x times slower than language X?" Or observe this set of web framework benchmarks: http://www.techempower.com/benchmarks/
It actually is trivial in a lot of cases. It's often as simple as swapping out lists for vectors and inserting a few strictness annotations into your types.
The good news is that it stops at the function boundaries. Your quicksort may be implemented in the ST monad, looking like some bastard child of C, but the function type ends up being
qsort :: Ord a => Vector a -> Vector a
And that's one of the likeable properties of Haskell: it doesn't deny that real-world programs sometimes require mutability, but allow you to isolate it through the type system. So, even though qsort may use mutable memory for sorting, it is a pure and referentially transparent function.Yes, my point was just that there are programmers using Haskell in a non-optimal way. Beginners seem to be surprised when their Haskell code isn't automatically in the upper level.
I'm not really a great fan of benchmarks, or this particular benchmark, but at least the source of every test is available:
https://github.com/TechEmpower/FrameworkBenchmarks/blob/mast...
https://github.com/TechEmpower/FrameworkBenchmarks/blob/mast...
https://github.com/TechEmpower/FrameworkBenchmarks/blob/mast...
No kidding:
http://benchmarksgame.alioth.debian.org/u64/program.php?test=regexdna&lang=ghc&id=2
It's mostly a matter of knowing C, then knowing how to torture GHC into doing what the C would do.http://benchmarksgame.alioth.debian.org/dont-jump-to-conclus...
After some experience, I think the biggest pain point in Haskell's syntax is that it is very light on keywords so many things that would show up as syntax errors in other languages might show up as type errors in Haskell. For example, forgetting a comma in a list will result in a function application between the two list elements instead of a syntax error.
There isn't actually that much in the way of actual syntax in Haskell (LYAH is a great place to start, don't just try to eyeball random code snippets), and it becomes preferable after some familiarity.
What will take time is learning new concepts, programming purely and learning the tools to manage effects.
I've spent more than 20 hours on Haskell syntax and feel like I am not even halfway there to "doing useful stuff".
EDIT: And I think time to be able to do something useful is a very important benchmark because after that point, further learning takes little effort or motivation.
Some libraries may define their own operators (Scala suffers from this too), which can be impenetrable. Some libraries are better than others.
Although, I don't consider defining new operator names part of the syntax of the actual language itself.
I guess I'd just hope one doesnt start out jumping in to a complicated library. Its easier to start with more foundational materials.
When I struggle with Haskell it's more "I don't understand the type of this" than "I don't understand the syntax". Syntax is the easy part!
One of Haskell's unique selling points is the fantastic ease with which you can build software that is correct-by-construction and concise at the same time.
For someone I'm mentoring, I recently came up with two examples of this [1][2].
I don't have time ATM to explain all the details (maybe someone else does), but based on them I intend to write in the near future a blog post titled "Using the expressive power of Haskell's type system to build software that is correct-by-construction". I'll submit the link to HN when that happens.
It will be part 3 of this[3] ongoing series.
[1] https://gist.github.com/dserban/11176875 [2] https://gist.github.com/dserban/11139419 [3] http://techblog.rosedu.org/haskell-part2.html
data Inches = MkInches Double deriving (Eq,Show)
There is newtype for this. (MkInches u) \+/ (MkInches v) = MkInches ( u + v )
First two pairs of parens are redundant. from_inches_to_cm vin =
MkCm (vin_as_pure_double * 2.54)
where
(MkInches vin_as_pure_double) = vin
Surely you want: inchToCm (MkInches x) = MkCm (x * 2.54)
In Haskell we use camelCase.Besides these fairly trivial mistakes there are simply better approaches for dealing with units.
Erlang's syntax is very similar to Haskell's, is it not?
If you just want to learn a FP language, I'd go with Haskell because you learn a pure FP language that teaches you all the concepts that you will encounter in half-breed languages :) .. people will love me for that comment.
Haskell doesn't have a cryptic syntax. The same complaint would be just as (in)valid leveled at any commonly used language. We're not talking APL here.
>There are so many great languages out there nowadays, Clojure, Go, Erlang.
Go does not belong in that list.
>I don't see where Haskell would be a better fit
For writing software. I realize that sounds snarky, but that really is the answer. To see the problem with your question, just turn it around. Where would clojure or go be a better fit than haskell?