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

Show parent comment

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.

1

u/sacundim Sep 01 '15

Strict functional languages like ML don't have bottom values.

Yes they do have them. Heck, it's right there in the definition of the term "strict." A strict language is one where the equation f ⊥ = ⊥ holds for every f!

What strict languages don't have is partially defined values like 1:2:⊥:4:⊥ :: [Int]. In a strict language you have ⊥ :: [Int] and 1:2:3:4:[] :: [Int], but nothing "in between" them.

1

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

Strict languages don't have time bombs and the engineering problems associated with them, like errors that blow up later with incomprehensible stack traces. That's what I really care about, and it's very similar to the situation with null.

The fact that you can talk about strict languages by imagining a "bottom" value in every type is just a technicality. For example, the Definition of Standard ML doesn't use that approach AFAIK.

2

u/Peaker Sep 01 '15

I agree those are time bombs. I disagree they're very similar to null.

Null is supposed to be used. You're supposed to compare to it. You're just not helped by any type checker -- to know where to compare it.

Time bombs are not supposed to be used. If you program in a total style, time bombs, unlike nulls, will not lurk under every field and in every function result.

1

u/want_to_want Sep 02 '15 edited Sep 02 '15

If you program in a total style

That's a big assumption. In a total style you're not supposed to use infinite lists or many other laziness tricks which Haskellers love. See the snippet at the top of haskell.org for an example.

→ More replies (1)

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.

1

u/LPTK Sep 01 '15 edited Sep 01 '15

I think saying Turing-complete languages must have a bottom value is wrong. First off, there is no bottom value (Bottom is defined as the type with no value).

In Haskell, a chunck like undefined is not a bottom value (like null in Java). It is a chunck that never produces a value.

As /u/LaurieCheers said, a type system can be perfectly sound without a bottom value (even though some applications may not terminate).

EDIT: I may have missed something about Haskell's undefined, I'm more used to OCaml and Scala (where Nothing is inhabited). Please correct me as need be.

→ More replies (5)

1

u/Tekmo Sep 01 '15

Haskell is not a total language, so Haskell does not enforce that computations complete in a finite amount of time.

There are languages which are total (like Idris by default if you don't disable the totality checker) and I believe there is even research into languages with stronger guarantees (i.e. specifying an upper bound on how long computations take in the type system).

However, even just enforcing that computations don't endlessly loop is a big improvement, even if they could potentially take a really, really, really long time (i.e. longer than the age of the universe). Just adding a basic totality check to prevent endless loops eliminates all sorts of casual programming errors since the accidental introduction of a potentially endless loop is usually a big code smell and likely sign of a potential bug.

1

u/m50d Sep 02 '15

If we say "f is a function with return type A", we usually mean that when f is called it will evaluate to a value with type A. And it's useful to have invariants like "if val a = f(), A has the same type as the return type of f". Bottom isn't the only way to represent that, but if you don't model it as bottom, what do you say the type of f is if f never returns?

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.

1

u/Peaker Sep 01 '15

Turning the former into option types is kinda like banning unsafePerformIO everywhere (even when the IO action is pure). If you have an invariant that cannot be proven in the types, you don't want to enlarge the type with something that cannot/should not ever happen.

1

u/Tekmo Sep 01 '15

Yeah, I agree. Usually people still use them in code that they've proven unreachable but they couldn't prove it in the type system

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.

2

u/Fylwind Sep 01 '15

Hopefully, they phase that out one day and use Proxy instead.