The Evolution of a Haskell Programmer (2001)
willamette.edu
willamette.edu
Phase 2: OK, but those bugs are my own programmer errors.
Phase 3: I admit it, I have no idea what I'm doing.
Phase 4: OK, I can't even figure out what the Haskell I did two years ago was even trying to do. I was smarter then.
1) They passed unit tests. 2) They passed a type checker.
If a bug did not cause a unit test to fail, then it passed the unit test suite. (Less cryptically, an empty set is still a set)
In any case, Rich Hickey probably had more context for his words.
10 (say) lines of code, 0 lines covered by tests, test coverage is 0/10. No division by zero, nothing undefined happening.
Similarly, not all diseases are prevented by vaccination, but that's not considered a good argument to stop vaccinating people against those diseases that are prevented by vaccination.
Instead, the focus should be on what else we can do to improve the bug detection rate. This is an area that needs further research (and I would start with the observation that the quality of the unit test varies dramatically depending on who writes them).
The type-checker prevents certain classes of bugs, inconsistencies in types, lots of silly typos and mistakes. But it doesn't fix errors in our logic or algorithms. The type-checker doesn't know you should have added instead of multiplied, nor does it fix conversion errors at the borders of our programs where we, say, write a Haskell data structure into a JSON file.
Dimensional analysis is a type system that knows exactly that.
s f g x = f x (g x)
k x y = x
b f g x = f (g x)
c f g x = f x g
y f = f (y f)
cond p f g x = if p x then f x else g x
fac = y (b (cond ((==) 0) (k 1)) (b (s (*)) (c b pred)))
is faster than this facAcc a 0 = a
facAcc a n = facAcc (n*a) (n-1)
fac = facAcc 1
and these are the first and second fastest.> Interestingly, this is the fastest of all of the implementations, perhaps reflecting the underlying graph reduction mechanisms used in the implementation.
Could anyone elaborate on this a bit more?
fac' f 0 = 1
fac' f n = n * f (n-1)
fix f = f (fix f)
fac = fix fac'
so if the second is indeed faster then explicit fixpoints beat tail recursion[1] https://en.wikipedia.org/wiki/SKI_combinator_calculus [2] https://en.wikipedia.org/wiki/B,_C,_K,_W_system
https://en.wikipedia.org/wiki/SKI_combinator_calculus
https://en.wikipedia.org/wiki/Fixed-point_combinator
The Y combinator (which is behind the name for this website) lets you define recursive functions without actually using recursion (the only recursive definition is Y itself, which is often available as a language primitive)
A less obfuscated version of the factorial using the y combinator would be this one:
fac' f n = if n == 0 then 1 else f (n - 1)
fac = y fac'
note how fac' is not recursive and instead calls its "f" parameter when it wants to do a recursive call. The y combinator then ties everything together by passing fac' to itself.The other obfuscating factor in that program are the S,K,B and C combinators. The purpose of these one is to let you write a program without any variable definitions or lambdas. Notice that when that program finally defines `fact`, it has the form
fact = y {some big expression}
where the big expression only has function applications and references to the previously-defined combinators. There are no mentions to the "f" and "n" variables that we had before. The neat thing about the SK family of combinators is that you can use them to build any function, not just the factorial:https://en.wikipedia.org/wiki/Combinatory_logic#Completeness...
As for the speed comment, one way to implement lazy evaluation, as found in Haskell, is to compile programs down to those SK combinators and then use graph reduction to evaluate the result. I would expect a reasonable Haskell implementation to be able to automatically generate the unreadable combinator version of the program from the usual definition of factorial that we all know and love but maybe there was a Haskell implementation back in 2001 that wasn't as reasonable?
https://en.wikipedia.org/wiki/Graph_reduction
https://en.wikibooks.org/wiki/Haskell/Graph_reduction
https://wiki.haskell.org/Super_combinator
That said, dunno how the more recent Haskell compiler handle things. Hopefully some other helpful HN-er can enlighten us here.
succChurch n f = n f . f
facChurch n f = n g (const f) id where
g f n = n (f (succChurch n))
toChurch 0 = const id
toChurch k = succChurch (toChurch (k-1))
fromChurch n = n succ 0
fac = fromChurch . facChurch . toChurchFunctional programming is arriving right now, but not as Haskell.
As an aside, I think of Haskell as a sensei/guru saying, "Young grasshopper, if you want access to the glory that is my wisdom you will have to wash my dishes and scrape off my calluses for the next three years" to which my personal reply is "Hell no". It¨s unfriendly and it doesn't respect my time. Is there wisdom in Haskell? Probably, but I don't have the patience to deal with the bullshit.
I don't think Haskell itself will ever be the language of choice, it'll probably fall into (remain in?) a smalltalk like life.
That said, functional idioms seem to be creeping into lots of mainstream languages, so it's not like never. Rust seems pretty heavily influenced by ml, and somewhat by haskell.
Mainstream languages have lambdas, more immutability and stronger types? That's great (non-sarcastically!). Haskell now has GADTs, rank-n types, polymorphic kinds, type families (poor name for type-level functions), and more.
These things make Haskell still quite compelling over other more mainstream languages, if you're willing to learn.
In some sense, yes. On the other hand, there are diminishing returns. As an example, the increase in software quality from a Java-like language adopting any of algebraic data types, parametric polymorphism or first class higher order functions is probably much bigger than Haskell moving to full on dependent types.
In any case, your point stands and complements mine.
(Apropos ADTs, did Scala always have them? From what I can tell their syntax is pretty awkward, though.
Google's Protobuf, which in some sense denotes a type system, even if not a programming language, did get something like ADTs: https://developers.google.com/protocol-buffers/docs/proto3#o...
I am pretty lenient, and would go for anything that resembles a compiler-enforced tagged union. (Think C-style union.))
http://www.boost.org/doc/libs/1_60_0/doc/html/variant.html ??? (and I think it's supposed to be coming in c++17)
either :: (a -> c) -> (b -> c) -> Either a b -> cIn the case of Haskell, it is taken as a badge of virtue, and it is a matter of faith that the problem is just that all other programming languages have mis-educated everyone who doesn't "get religion" about Haskell.
If Haskell's interface is hard to understand, that is a problem with Haskell.
Evidence that Haskell was deliberately made difficult to understand? And supposing this were true, why hasn't anyone made the interface more intelligible?
> If Haskell's interface is hard to understand, that is a problem with Haskell.
That's a bit like saying that if the mathematics used in the General Theory of Relativity is hard to understand, it is a problem with the General Theory of Relativity.
Well, but that's true; if there were easier-to-understand mathematics that had equal utility, it would be superior. The math being hard to understand is a problem, but (as far as anyone can tell), its a necessary cost with General Relativity.
So, for Haskell -- granting, for the sake of argument, that it is particularly hard to understand (which I'm not sure is really the case) -- the question is the complexity a necessary price for some benefit that is worth the cost?
And before you think I'm just hating on Haskell, the same is essentially true of Lisp as well.
I'm not sure how this is different than introducing a block in C.
What would be the C equivalent of:
(let ((last-response))
(defun get-response ()
(print last-response)
(setf last-response (read))))
(print (get-response))
(print (get-response))
Notice that no other function can use last-response. It only exists for get-response, but it exists outside the scope of get-response. Does C have this?Since the variable in question is only used in one function, you could declare the variable static to that function. It takes some care to make this reentrant, but that's possibly the case in lisp as well.
To share between multiple top-level functions, you can only limit scope to the individual file.
The bigger thing C can't do that lisp can here is defining new functions in arbitrary places. In C variants where you can define local functions, you can indeed capture variables in local scope. And within a function, you can limit scope by creating a new block:
int test() {
int foo = 7;
{
int foo = 9;
}
return foo; // returns 7
}
Even in those C variants, you can't place a new function in global scope from within a function. (let ((x))
(defun func1 ())
(defun func2 ()))
This is what I mean when I say explicit scoping. And it means that the reader/debugger/maintainer knows that this variable only exists for these functions. A static variable's scope is implied by the scope of whatever it's defined in (not sure if that's limited to functions in C), in this case X exists outside of C and has it's own scope, not just it's own extent.Yes, I mentioned that static variables in a function would not extend to multiple functions.
You can share a variable between a restricted set of top level functions by grouping those functions in a single object file that does not expose the variable in question.
I think my only objection is that your phrasing implied what's different is the explicitness of the scoping, when it's actually the flexibility of how functions can be defined (unsurprising, from a lisp).
You can overcomplicate things in any language. Haskell gives you better tools for dealing with complexity - which some people use as a reason to push the complexity to the limit. But if you stick to abstractions that are actually providing value (e.g. by letting you reduce code duplication) you'll find it's a very good language.
Though, if you need hard real time, even C can be tricky.
Haskell can be written for soft real time things, but it's also tricky. Rust might be a better bet?
A lazy language is probably not the answer to this particular problem.
All tests are thus 100% reliable and parallelizable.
This capability of isolating and controlling side effects makes Haskell very uniquely well-suited to applications that need to withstand a lot of maintenance by a lot of people for a very long time.
The general high-level approach is that your business logic functions run in some monad, constrained by the set of capabilities it requires. Each capability is represented as a typeclass.
Your type signatures say that your business actions work in every monad that supports those capabilities, so the type checker rejects any code that tries to use "unblessed" side effects.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def factorial(n):
return 1 if n == 0 else n * factorial(n-1)
def factorial(n):
return eval('*'.join(map(str, range(1, n+1))))
def factorial(n):
return reduce(lambda x, y: x * y, range(1, n+1))
def factorial(n):
def facts():
n, r = 1, 1
while True:
r, n = n*r, n+1
yield r
return next(islice(facts(), n-1, None))
The difference is: historically, Haskell was an experimental language, a test-bed for trying out new and weird ideas, which meant that experimentation with style has been pretty normal thing. Haskell "culture" encouraged being clever, because that's how you found new, interesting ideas. On the other hand, Python doesn't have that legacy: most of the implementations above are non-idiomatic because they're too clever.So yes, you can write things lots of ways in Haskell. But, if you had production code in Haskell, you wouldn't try to be clever, in the same way that you wouldn't (or shouldn't) try to be clever in production code in Python. You'd write simple, straightforward code, just like
fact n = prod [1..n]It doesn't mean that the language design is going to somehow ensure there's only one way (even only one idiomatic way) for users to implement any particular algorithm. It doesn't mean everyone has to use the same web framework. It's really not prescriptive, except for Python itself.
The vast majority of examples on the page are curiosities which appeal to some people and arise from all the academic attention both given to Haskell and which Haskell permits. You can be a competent and highly-effective Haskell programmer without understanding the majority of these.
"Maybe" still blew my mind away first time I saw it...MAYBE?? MAYBE?? :D. Sure it would all be beautiful if I spent time learning it.
In practice, there are some of the examples that are more important than the others:
- The "accumulating" version might use less stack-space than the naive recursion so its a very important technique to learn.
- The foldl version is a more structured version of the accumulating version, kind of like how a for loop if is more structured than a goto.
- The memoizing (aka caching) version is useful if your funcion is very expensive to compute.
- And the "tenured professor" obviously makes the best use of the existing syntactic suger :)
The rest of the entries are a bit more overkill for a factorial program.
In light of that, I would definitely recommend Haskell over other languages for any use cases where you expect you're going to be wrong, repeatedly, about how best to structure your program. Especially in domains that aren't known very well or when the demands on the program are likely to be highly dynamic.
Though really, at this point I would tend toward using Haskell when there is not much reason to pick something else.
There's this helpful site that suggests libraries for various things: http://haskelliseasy.com Someone should make a companion site listing snippets of code for common tasks showing plain ways of doing things.
While I would also like more production Haskell examples, I wouldn't read much into this webpage—it's basically just a 15 year old joke.
You'll probably recognize some companies, such as Facebook, Google, Microsoft.
Every time I read a comment like this it reminds me how much fashion and an unsubstantiated cult of "viable for production" publicity steers the industry instead of curiosity and experimentation.
LMGHTFY: https://github.com/search?l=&o=desc&q=language%3AHaskell&ref...
It's also used for a bunch of tricky data manipulation problems that were harder to solve using pure SQL. Example: identify a unique customer based on attributes (email, phone, address, etc.) one or more of which can change when a customer tries to create a "new" profile to grab the $10 new customer signup voucher. This ran recursively on the entire customer dataset (12 countries, some customers had created as many as 250 profiles) in about 4 seconds on a m3.medium instance.
We don't/didn't write blog posts or tweets about it though. I think the set of people who write blog posts (i.e. both have free time to do so, the talent, and the motivation) is relatively small, and the number of blog posts and other visible stuff being published is proportional to the size of the community, so you'll see many more Node.js/RoR posts than you will on using set theory to reduce a 5,000-table flawed data model systematically or the kind of everyday stuff Haskellers are doing everywhere. Also, personally at least, I don't feel like I know enough to have much to offer by writing a blog, so I stick to making these semi-anonymous HN comments.
Interviewing Haskellers, I found a lot of examples of similar work - CRUD tasks, web services, etc. built in Haskell within a larger organisation and running quietly in the background. Something small and modular that can be tacked on quietly.
One of the creators of Servant moved on to Tweag [2], a French big data company, where he's working on PB-size distributed machine learning projects for large corporate clients, which I think is where Haskell really shines today. I suspect NDAs will stop them from talking much about it... I've always wanted to do similar work for clients but so far, no dataset was "big" enough to justify moving away from well established R libraries.
Anecdata: Haskell pays my bills and I've never coded a factorial function at work.
A Haskell program I wrote to find and match subtitle files for a particular release of the movie I have.
it's kinda wasteful to keep making the cells, but it's easy to read. shrug
however ghc is very smart. it might be clever enough to optimize away the cells. it might also do immediate ints, rather than pointers to '1', i'm pretty hazy on when there's an int, and when there's a bigint.
main = print $ product [1..100]
ghc-core-html --ghc-option=-ddump-simpl --ghc-option=-dsuppress-all fact.hs
https://rawgit.com/jonschoning/c4ad2129aa7d258e65f9/raw/f8ed...you can see
main_go (plusInteger x_a3Sq main4) (timesInteger eta_B1 x_a3Sq);
where it compiles to a recursive loop with an accumulatortypicall the [1..100] gets compiled to (enumFromTo 1 100) and it can be desugared further..
so, yeah, foldmap compiles to foldr which may compile down further
GHC rewrites most of the common built-in functions to eliminate intermediate trees and lists. You can see a list https://downloads.haskell.org/~ghc/7.0.1/docs/html/users_gui... (section 7.14.4; ctrl-f "good producer").
I admit now I am stuck looking at http://hackage.haskell.org/package/base-4.8.2.0/docs/src/Dat... as it uses foldMap which I am not used to. According to https://wiki.haskell.org/Fold foldl can make use of TCO. When I get some time I will see if I can produce the thunks as I am very interested i this!
Tendency to pile up useless crap^Wabstractions is the cause of suffering.
Imagine that your doctor and financial adviser are doing this. Hey, wait a minute...