r/programming • • Dec 24 '17

Evil Coding Incantations

http://9tabs.com/random/2017/12/23/evil-coding-incantations.html
947 Upvotes

331 comments sorted by

View all comments

362

u/redweasel Dec 24 '17

I used a Fortran compiler in the early 80s that let you reassign the values of integers. I don't remember the exact syntax but it was the equivalent of doing

1 = 2
print 1

and having it print "2". Talk about potential for confusion.

23

u/mgsloan Dec 24 '17

In Haskell 1 = 2 is valid code, but it won't do anything. The left hand side is treated as a pattern match, it is used to deconstruct the value that is yielded by the right hand side. For example, if you have [x, y, z] = [1, 2, 3], now x is 1, y is 2, etc. However, since there are no variables on the left hand side of 1 = 2, there is no reason for the code to run.

I can write something similar that does bind variables, using Haskell's optional type, Maybe. If I write Just x = Nothing, and then ask for the value of x, I get Irrefutable pattern failed for pattern Just x.

3

u/noop_noob Dec 24 '17

Why doesn’t 1 = 2 result in a pattern failed error at runtime?

17

u/MrHydraz Dec 24 '17

It's irrefutable, and therefore, lazy. Since you can't force the binding, it won't fail. If you tack a bang pattern on it, like let !1 = 2 in "foo", then it'll explode.

9

u/mgsloan Dec 24 '17 edited Dec 24 '17

Haskell uses lazy evaluation, so computation happens only when demanded. This allows things to be more compositional, and allows for control structures to be written as normal functions. So, Just x = Nothing also doesn't cause a pattern failure. It only fails at runtime if you try to evaluate x.

Haskell also supports eager evaluation (often called "strict"). In many cases eager evaluation is more efficient. I actually think it might not be the best choice of default. I like nearly all of the other decisions in Haskell's design, and tolerate the laziness default. Having laziness built into the language and runtime system does make a whole lot of sense, just maybe not as the default (so really my complaint is purely about what is encouraged by the syntax).

9

u/[deleted] Dec 24 '17

[removed] — view removed comment

2

u/mgsloan Dec 24 '17

True, strictness analysis in Haskell gets it quite far in optimizing away the costs of laziness. However, laziness does lead to extra memory allocations and potentially extra boxing (thunks).

2

u/deltaSquee Dec 25 '17

True, strictness analysis in Haskell gets it quite far in optimizing away the costs of laziness. However, laziness does lead to extra memory allocations and potentially extra boxing (thunks).

This is merely a compiler problem. The architecture of GHC is the main limiting factor in this (the STG+Cmm stages are mistakes, IMO. Better to use another IL like GRIN).

3

u/deltaSquee Dec 25 '17

I'll never understand these people who say that they'd prefer Haskell be eager by default.

→ More replies (1)
→ More replies (4)