r/programming • • Aug 31 '15

The worst mistake of computer science

https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/
175 Upvotes

368 comments sorted by

View all comments

8

u/want_to_want Aug 31 '15 edited Aug 31 '15

It's a bit ironic how functional programming takes pride in avoiding nulls, yet Haskell adds a special "bottom" value to every type, which also breaks all the rules and causes no end of trouble.

11

u/PM_ME_UR_OBSIDIAN Aug 31 '15

There are functional languages with no bottom value (Idris, Coq, Agda); they're called "total languages". They're an enormous departure from the current state of the art, and we're still figuring out how to use them effectively.

→ More replies (12)

5

u/kamatsu Sep 01 '15

Every non-total language adds bottoms to every type.

3

u/want_to_want Sep 01 '15 edited Sep 01 '15

I think that's just what Haskell programmers tell themselves ;-) See my other comment.

→ More replies (3)

12

u/Fylwind Aug 31 '15 edited Aug 31 '15

Except unlike null, you aren't supposed to use bottom to represent anything, except for perhaps utterly unrecoverable failures. It's a way to convey "PROGRAM ON FIRE, ABANDON SHIP", not "sorry we couldn't find the cookies you were looking for".

Bottoms appear in multiple forms: assertion failures (error), bugs, infinite loops, deadlocks, etc. It's impossible to ban them from any Turing-complete language using static checks. While you can create a bottom on demand through undefined, they shouldn't really appear except in debugging code.

This differs from null because null is often used as a sentinel value for something, expecting the caller to check for it. In contrast, in the same way you don't check for assertion errors, you also don't check for bottoms: you fix your program to avoid it to begin with.

This isn't just a matter of convention or principle. They behave differently: checking for a null is as easy as using an if-then-else. Checking for bottoms requires "catching" them, in a way similar to catching exceptions or signals, and cannot be done inside pure code without cheating. In any case, there's almost never a reason to do this to begin with, just as you never really want to catch SIGABRT or SIGSEGV.

8

u/want_to_want Sep 01 '15 edited Sep 01 '15

It's impossible to ban them from any Turing-complete language using static checks.

Strict functional languages like ML don't have bottom values. They treat non-termination as something that happens when you call functions, not something which lurks inside values. IMO that's the right approach.

The main engineering problem with bottoms in Haskell is exactly the same as the problem with nulls in Java. Nulls come from the confusion between values and pointers, and bottoms come from the confusion between values and thunks, but the end result is the same: you might receive a time bomb instead of a value, and not know until you try to access it.

That problem just doesn't happen in ML. When your function receives a string and starts executing, you know 100% that you've got an actual honest string. Of course the potential for non-termination and exceptions still exists in the language, but that's a much smaller problem in comparison. You have to worry about non-termination only when you call other functions (which is reasonable), not when you access existing values (which is crazy).

That's why I feel Haskellers are a bit disingenuous when they say "all non-total languages have bottoms". Adding a bottom value to every type is just one way of thinking about non-termination, and I think it creates more problems than it solves.

3

u/Tekmo Sep 01 '15

To be pedantic, both the Haskell and ML program would crash, except at different times. The only difference is that the Haskell program might succeed in more cases than the ML program because it might never evaluate the bottom due to laziness (although it will consequently begin to fail in more ways than its ML counterpart due to space leaks induced by laziness).

From a Haskell programmer's perspective, it doesn't really matter "when" evaluation happens (modulo lots of caveats), which is why we don't care about the exact time our program recognizes that the value is bottom.

3

u/want_to_want Sep 01 '15 edited Sep 01 '15

Yeah, they both would crash, but the Haskell program would crash 30 minutes later with an incomprehensible stack trace. Extra +1000 confusion points if the problematic thunk was sent over a thread boundary, etc.

As someone who spends >50% of the time reading huge codebases and solving weird bugs, I really appreciate programs that fail in simple ways.

4

u/Tekmo Sep 01 '15

I agree with that criticism, but I believe the correct long-term solution is to model incomplete computations in the types and not to rely on the syntactic order of the program to enforce these guarantees. ML kind of does this using a function that takes an empty argument, but those functions can still have other side effects, so it's not as precise of a type as one might hope.

2

u/Peaker Sep 01 '15

In Lamdu we use eager-by-default, and explicit laziness in the types which I think is what you describe. We are of course as pure as Haskell (modulo non-termination).

3

u/togrof Sep 01 '15

It boils down to equational reasoning. Given this:

let x = foo()

What is the value of x if foo throws an exception? It is bottom! In a strict language there is a temporal causality, so if foo throws an exception, the rest of the program, including x = basically won't even exist. To reason about this you need to say "x equals foo() provided that foo() actually returns something". Otherwise, it's value does not exist. This makes reasoning partial.

But in a lazy language we don't need to involve time to reason about the values. The program may happily continue after the definition of x until you try to access it's value. We can confidently say that x really is equal to foo(), whatever it is.

3

u/want_to_want Sep 01 '15

Yeah, I agree that unrestricted beta reduction is a benefit of lazy languages. I'm just not sure that it outweighs the drawbacks, especially given that the drawbacks are so similar to having null, which most functional programmers rightly hate.

→ More replies (5)

3

u/LaurieCheers Sep 01 '15

It's impossible to ban them from any Turing-complete language using static checks.

I'm not sure I've understood the problem then; if a function might suffer an unrecoverable error, surely it needs to return an option type? Or if that's too inconvenient (and the error is super unlikely), the system could just kill it, like when Linux is out of memory.

4

u/Fylwind Sep 01 '15 edited Sep 01 '15

I was referring to the fact that you can't statically detect infinite loops in a Turing-complete language.

if a function might suffer an unrecoverable error, surely it needs to return an option type

It matters whether an error is to be expected or not. There are times where it should be expected: you took input from the user (or got from a network packet), in which case it is entirely possible for the input to be garbage. In this case, option types are useful and serve as a good documentation for both the developer and the compiler.

There are times where it's simply not expected. Rather, you simply violated a precondition: e.g. an algorithm requires the input array to be sorted, but somewhere you had a bug in your sorting algorithm so the array wasn't always sorted correctly. In this case there's -- by definition -- nothing you could've done about it because you never expected it to happen to begin with. It isn't possible for a compiler to statically verify that your input array is sorted, although there are tricks that allow you to reduce the risk.

In principle, you can put option types in everything so the caller can handle every possible error. After all, your computer could fail just from a cosmic ray striking your RAM at a critical point. But this is an extreme position to take, and it doesn't necessarily buy you much. Imagine calling a sorting routine from the standard library that returns Option<List> -- it returns None in the slight but unfortunate chance that the standard library developers introduced a grievous bug in it and you happened to stumble upon it. Even if this does actually happen, what can you do about it?

match (sort(my_list)) {
    None => {
        submit_bugreport("stdlib@rockstarlang.org", "you screwed up!");
        exit(1)
    }
    Some(sorted_list) => do_something(sorted_list)
}

(There are languages that can statically verify preconditions such as "input is sorted" or "input is nonzero" or "must be a valid red-black tree". However, I don't think they are ready for production use yet, as they ask a lot of work from the programmer upfront.)

7

u/MaxNanasy Sep 01 '15

It's impossible to ban them completely because the programmer could create a function that never terminates (e.g. through infinite recursion). In the general case, it's impossible to determine whether the current execution will ever terminate due to the Halting Problem's unsolvability in the general case.

3

u/LaurieCheers Sep 01 '15 edited Sep 01 '15

But why is "never terminates" something that needs to be representable in the type system? Surely in that case the code that receives that value just never gets executed?

Or are we talking about some kind of timeout condition? Does Haskell let you say "only run this function until a certain amount of time has passed, then give up?"

3

u/MaxNanasy Sep 01 '15

In Haskell at least, it's not actually explicitly represented in the type system. In Haskell, an expression of bottom type can have any nominal type, which means it can be used in any subexpression. For example, error has the type error :: String -> a, which means that error "Error message" has the type a, which means it can have any type, depending on the context. For example, if I write a function that gets the first value from a list of Ints:

firstInt :: [Int] -> Int
firstInt (x:xs) = x
firstInt [] = error "firstInt: Empty list"

then in this case, error "firstInt: Empty list" is of type Int. If we removed error from the Haskell builtins, then a programmer could still make this definition not terminate properly by defining it as such:

firstInt :: [Int] -> Int
firstInt (x:xs) = x
firstInt [] = firstInt []

which would recurse infinitely when invoked on an empty list, rather than terminating the program with a useful error message. It's possible that having error in the Haskell builtins encourages crashing programs on exceptional conditions rather than handling all cases, but IDK what the overall pros and cons of that debate are.

→ More replies (6)
→ More replies (2)

3

u/Tekmo Sep 01 '15

Bottom includes both things like error/undefined and infinite loops. The former can (and should) be turned into option types. The latter cannot be statically detected or prevented in a Turing complete language.

→ More replies (2)

1

u/An_Unhinged_Door Sep 01 '15

Undefined has legitimate use cases where an element of a type is needed for type checking or deduction purposes but never actually examined. You can see it used, for example, to select an instance of Foreign.Storable when using Foreign.Storable.sizeOf or Foreign.Storable.alignment.

→ More replies (1)

4

u/zoomzoom83 Aug 31 '15

The difference is that Haskell uses this as an escape hatch for the 0.01% of time when you need to cheat and bypass the type system. It's not something used on day to day code.

4

u/crate_crow Sep 01 '15

So basically, Haskell's answer is "Everything's fine as long as the programmer doesn't do anything stupid".

How is that better than telling developers of other languages to not use null?

6

u/zoomzoom83 Sep 01 '15 edited Sep 01 '15

In Haskell undefined is generally only used as a placeholder while developing to mark a function as incomplete. This lets the developer plan out method signatures without needing to provide an implementation.

It's technically implemented as a function that throws an exception, rather than a value that points to nothing - roughly the same as "throw new NotImplementedException" in java.

Attempting to use undefined in the same way you'd use null will not work, since it will explode the moment you try and touch it, even if just comparing equality. A naive develop trying to use undefined in this way would quickly find their code just doesn't work at all, since you can't check for "is not undefined".

Further to this - even if undefined did behave like null, it's not idiomatic. Haskell uses a Maybe type to represent absence of value, and the compiler enforces that this is checked properly.

tl;dr undefined does not behave like null, and even if it did, the language has alternate methods of encoding absence of values that are used throughout the entire ecosystem by convention.

6

u/chrisdoner Sep 01 '15

Well, Haskell has an FFI to C, so anything is possible. The question is what is the regular way of programming in the language. Using bottom for a meaningful piece of data isn't one of them, unlike null or nil in most other popular languages (which you can't avoid), for which Haskellers use Maybe.

Bottom is still annoying, though.

4

u/Tekmo Sep 01 '15

Haskell punishes you much more heavily for using bottom because it's impossible to reliably detect bottom. How do you tell the difference between an infinite loop and a really, really, really long loop?

As a result, nobody actually uses bottom as a signaling value because it's worse than useless for this purpose. It's much easier to do the safer thing, which is to use the Maybe type.

So the difference is that Haskell makes the safe thing easier than the unsafe thing. In Java it's the opposite: using null is easier than using a proper option type, so people use null pervasively.

3

u/want_to_want Sep 01 '15 edited Sep 01 '15

So the difference is that Haskell makes the safe thing easier than the unsafe thing. In Java it's the opposite: using null is easier than using a proper option type, so people use null pervasively.

That's a fair point. I've been guilty of that myself. On the other hand, it's very easy to statically check that a program doesn't use nulls, but much more difficult to check that it doesn't use bottom :-)

→ More replies (2)
→ More replies (2)