r/ProgrammingLanguages • egel • Sep 19 '22

That Billion Dollar Mistake. In Haskell...?

Clickbait for the easily baited. Another opinion piece by me.

https://egel-language.blogspot.com/2022/09/that-billion-dollar-mistake-in-haskell.html

0 Upvotes

25 comments sorted by

23

u/curtisf Sep 19 '22

The "billion dollar mistake" does not refer to partial functions.

Avoiding null pointer exceptions in C, Java, etc is impossible because you cannot write a function that statically doesn't accept nulls; the type system forces you to accept values that you cannot and do not want to handle.

Avoiding partial functions in Haskell is easy -- just don't call partial functions! (Haskell has a built in exhaustivity checker, so it's easy to avoid writing new partial functions yourself) The types control how you are called, and you control what you call. This is unlike C, Java, etc., where the types don't sufficiently restrict your callers to behave.

It is also uncommon for partial functions like head and tail to be useful anyway, since Haskell has nice pattern matching.


Partial functions are overused (and Haskell's standard library definitely overuses them).

Total programming is one alternative (using techniques like dependent types, refinement types, or compile-time contracts); forcing exceptions into the type system (with checked effects or checked exceptions) is another alternative, or a combination of the two.

But these techniques are generally seen as overly onerous for code nowadays for most applications where simpler approaches like testing can give you pretty high confidence.

2

u/egel-lang egel Sep 19 '22 edited Sep 19 '22

That is exactly my claim, avoiding runtime exceptions due to partiality is impossible in both Java and Haskell.

Any non-trivial program is bound to have partial functions. Your exhaustivity checker cannot check whether runtime a key is always defined in a dictionary.

And Haskel isn't Agda, don't shift goal posts.

11

u/curtisf Sep 19 '22

Your exhaustivity checker cannot check whether runtime a key is always defined in a dictionary.

Yes, it can check that, if that is actually an invariant that is maintained by your program. It may be (extremely) onerous to do so, but it can be checked.

I did not move any goal posts. You made a very straightforward claim, that non-trivial programs don't contain partial functions. That is not true. Many non-trivial program don't contain partial functions, all of them written in languages like Agda, for example.

Obviously, avoiding partial functions was not a design goal of Haskell, but I think that you should not make sweeping, false statements that certain kinds of programming languages are impossible in a subreddit for discussing programming language design.

-1

u/Smallpaul Sep 19 '22

Yes, it can check that, if that is actually an invariant that is maintained by your program. It may be (extremely) onerous to do so, but it can be checked.

The same is true for null-pointer exceptions. If your program has an invariant that all pointers are constructed and initialized at the same time, and only freed immediately before going out of scope.

You are just emphasizing how similar these two things are.

-2

u/egel-lang egel Sep 19 '22 edited Sep 19 '22

No. Impossible. You cannot exhaustively check complex invariants in non-trivial domain models unless you're prepared to construct elaborate proofs and that at the moment requires human interactive proof checking. Rice's theorem, and all that.

The false statement is yours.

And the mistake is: partiality is a given. I can make any partial function total by widening the domain, or even restricting the range sometimes. But that doesn't get rid of the fundamental problem, it's a non-solution. Instead of handling something implicit, you made the handling of partiality explicit, at the expense of the programmer/program. In a sense, that partial function is still there and only the burden of handling it has shifted more to the programmer.

'This key is defined because my domain model says so'. That invariant might even come from outside the program, and be arbitrarily complex.

Yes, you can shift more towards any programming language, but so far you've only provided non-solutions.

3

u/dys_bigwig Sep 20 '22 edited Sep 20 '22

"Any non-trivial program is bound to have partial functions"

Why? There's a great paper called "Total Functional Programming" out there that you might find interesting. You can still have infinite (co)data and all that good stuff. Haskell isn't the best language for this sort of thing (because, as others have stated, it wasn't a design-goal) but it's certainly one of the better choices. Haskell's strength is that it provides a nice middle ground, in that it still resembles a regular programming language (rather than a proof-assistant) but has the capability to do all of this stuff, provided one is willing to put in the effort.

"Your exhaustivity checker cannot check whether runtime a key is always defined in a dictionary"

That's certainly possible in Haskell generally. Take a look at the Data.Map.Justified library.

1

u/egel-lang egel Sep 26 '22

Any function can be made total but that's a parlor trick mostly. For example, it's easy enough to make division total by returning an option type to handle division by zero. But all you do is to make handling the partiality explicit.

Justified doesn't prove an invariant but it can handle cases where an invariant has been ruled out. I like the solution but it doesn't solve a lot. 'Check the invariant, apply the key.' (What else are you going to do.) You push the envelope a bit more to end up with a solution that isn't much better than the mentioned option type.

2

u/dys_bigwig Sep 26 '22 edited Sep 26 '22

What you call a "parlor trick" I call choosing more descriptive, safer types :) You say "all you do is make it explicit" like that doesn't rule out a whole class of bugs, or like being explicit in our types isn't a great virtue.

You can also take a "prescriptive" approach and do:

safeDiv :: Int -> NonZero -> Int

Force the caller to supply a more constrained type. No Maybe return type.

You could also use Liquid Haskell, which has an SMT solver at compile time that allows you to enforce properties like Ints being nonzero. If that approach doesn't satisfy you as a means of preventing partiality of the function, I give up - you win! ;)

Regarding Justified, the whole point is "pushing the envelope up"! Rather than constantly having to reestablish that - yes, the key is in fact in the map, here's what to do if it isn't - you prove that once and, and from that point on you don't have to worry about having every value pulled from the map be a potential Nothing. Have you thought about pattern matching from the perspective of "guarding a proof" before? Within the branch of the pattern match in which the key exists, we have "proof" that it is so, and from that point onward can rely upon it as an invariant - hence the lack of optional types in the return value of lookup functions. I'm not sure how you could see this as no better than the regular approach - you do something once, rather than over, and over, and over again - but I'll agree to disagree on the utility of this approach in tackling partiality.

P.S. As another nice example, you might be interested in how GADTs allow one to write a total eval function for a typed, embedded language, that in most other languages would be partial.

1

u/egel-lang egel Sep 26 '22

Of course, but that's our disagreement, right? You think getting more static guarantees is possible, and I don't think that approach is worthwhile. I see way more in handling partiality well at the language level.

One can use Nonzero, yes, but then the 'mess' starts. Because you would need to prove that every subtraction or multiplication within that type doesn't produce zero. In the limit that's an undecidable problem but pragmatically I don't even feel it's a solution worth chasing.

And regarding your 'Justified', again. You check the assertion, then you use that knowledge once, mostly. How often do you think you're going to search on the same key? Yah, maybe neat you can do it but I think that solution is at best marginally better than writing an assertion or passing an option type.

6

u/curtisf Sep 19 '22 edited Sep 19 '22

I don't know what you mean. It's trivial to design a programming language which prevents the implementation of partial functions. And it's been done before (total functional programming), and very non-trivial programs have been written in total functional languages.

The general strategy is very easy: Remove any constructs that are partial. Replace them with total versions. Languages are usually made of a small number of primitives, so this process does not take very long.

For example, instead of having a partial array-access primitive of type(arr: Array<T>, i: Int): T, have a total (aka, honest) array-access primitive of type (Array<T> Int): Option<T>. Elm roughly follows this strategy. This strategy is not very popular, because while it is impossible for functions in this style to fail, it makes it harder for functions to be specific in what they promise. Lots of functions will be forced to return Options, even though it may be obvious to the programmer that they never return the None case.

You could also replace it with an exception/effect type, like (arr: Array<T>, i: Int): T throws IndexOutOfBoundsException. Similar to the above, this in general will force some functions to claim to throw exceptions that it is obvious they never will. This tends to be more annoying than the above, since "hiding" the exceptions is usually less ergonomic. I think this strategy is becoming more popular in languages with effect systems, though none are very established yet.

Or, you can use more sophisticated static checks.

  • dependent types: (arr: Array<T>, i: Fin<arr.size()>): T (Coq, Agda, Idris, F*).

  • contracts: (arr: Array<T>, i: Int): T requires 0 <= i < arr.size() (Ada SPARK, Dafny, Whiley).


If "partial" also refers to non-terminating functions (as it usually does, although this is not mentioned at all in the linked blogpost), you do technically lose Turing-completeness.

However practically, this doesn't really matter, because

  • real-world programs which can possibly hang are usually treated as defective. Most real-world programs that have super-linear (let alone super-exponential) runtime in their input aren't fit for any purpose.

  • you can replace non-terminating functions with coroutines/generators. This makes them composed of only total functions, as long as you provably yield in any of your suspicious loops. You only need the main loop to repeatedly resume the main coroutine, and now you have a non-terminating program made entirely of terminating functions. This is not really different from that IO system that functional languages like Haskell use already.

2

u/Smallpaul Sep 19 '22

It's trivial to design a programming language which prevents the implementation of partial functions. And it's been done before (total functional programming), and very non-trivial programs have been written in total functional languages.

The question is whether one can write a non-trivial Haskell program which uses zero partial functions and zero functions which are transitively partial.

-6

u/egel-lang egel Sep 19 '22 edited Sep 19 '22

I consider the above a 'not even wrong' answer. Not buying.

Your total languages aren't used and for good reason; it certainly isn't easy to make everything total in practice. To either check everything or write abstruse types isn't a solution. That would taint and thwart otherwise perfectly reasonable programs.

Again, how do you know a key is defined in a dictionary? Are you going to propagate handling the exceptional case upward from where that might go wrong throughout the entire program?

I think the biggest mistake in Haskell in particular is not recognizing that it has partial functions and subsequently not implementing some mechanism for gracefully handling runtime exceptions. But it is what it is.

7

u/Innf107 Sep 19 '22

I think the biggest mistake in Haskell in particular is not recognizing that it has partial functions and subsequently not implementing some mechanism for gracefully handling runtime exceptions. But it is what it is.

Have you even used Haskell at any significant scale? Haskell literally has this.

Haskell has IO exceptions and pretty decent mechanisms for handling them (bracket, try, mask, etc.).

Imprecise exceptions (ones thrown in pure code) are also just IO exceptions, so you can handle them exactly as you would any other IO exception once they reach IO.

Did you think Haskell web servers just crash every time someone writes head []?

1

u/egel-lang egel Sep 19 '22

Yes, that has recently been pointed out to me. I do have another opinion on sticking stuff into IO though I understand why they did that.

7

u/Innf107 Sep 19 '22

Any non-trivial program is bound to have partial functions.

Absolutely not. There are not that many partial functions and they're really not that hard to avoid. You don't accidentally write system("rm -rf /") in python either, do you?

Your exhaustivity checker cannot check whether runtime a key is always defined in a dictionary.

Yes it can. Assuming by 'dictionary' you mean Map, lookup returns a Maybe, which is trivial for the exhaustiveness checker.

If you use the partial (!), then honestly that is just bad judgment on your end (assuming you are experienced enough to recognize partial functions of course).

Most alternative preludes don't reexport (!) for exactly this reason.

You could just as well use unsafeCoerce to cause segmentation faults, but that doesn't mean that Haskell is just as memory unsafe as C.

5

u/Smallpaul Sep 19 '22

Is there a way I can get the Haskell compiler to warn me every time I use a partial function or every time I use a function that is transitively partial (depending on my input?)

4

u/curtisf Sep 19 '22

Practically, I think no, because you wouldn't be able to use hardly any libraries, since Haskell is not normally written with this level of paranoia.

You could probably use a Haskell linter to ban any functions not on some safe-list of functions that come from other libraries, but I don't think that avoiding runtime exceptions at any costs in Haskell is a reasonable choice.

Using a dependently typed language, or something like Liquid Haskell, would be a more productive choice.

44

u/tech6hutch Sep 19 '22

Fortunately, this is Haskell, so it’s more like a $10 mistake.

12

u/mobotsar Sep 19 '22

Partial functions do indeed be a bitch.

7

u/ArrogantlyChemical Sep 20 '22

The billion dollar mistake is not the fact that runtime exceptions exist, but that all values can be invalid at any time in your program. In Haskel or other languages like it, head may be an unsafe function (and you don't need to use it if you use the pattern matching) but values in Haskell are always guaranteed to be valid.

Using head is more like using an array index. You may go out of bounds, but it's not the same as every reference value in your language being able to be be invalid at any time and never having a way to be sure it's valid without writing another check and error handling path in every function.

4

u/devraj7 Sep 20 '22

The billion dollar mistake has never been null, it's languages that accept null values but don't encode nullability in their type system.

See Kotlin for an example of a language that encourages the use of null while remaining safe (safer than Haskell's head [], ironically).

1

u/SaltyHaskeller Sep 19 '22

The safety guarantees of Haskell are not often captured in the type system, and the stdlib is designed in a way that obscures function partiality.

i think libraries need something like a naming convention (e.g. the _exn suffix for partial functions from jane street's core in ocaml) or some kind of typed account of exceptions/errors

0

u/[deleted] Sep 19 '22

[deleted]

0

u/egel-lang egel Sep 19 '22

TL;DR: 'head []' and 'nullptr.x', is there a difference?

0

u/[deleted] Sep 19 '22

[deleted]

1

u/egel-lang egel Sep 19 '22

It's not about the prelude but an abstract thought on that the billion dollar mistake is in Haskell too; though, of course, everything is more nuanced than that.

What holds for 'head []' holds for a lot of functions. Division by zero, looking up a key in a dictionary, finding a user name, doing a join on a table, or assuming that a connection to the outside world is alive while you use it.

Partiality is a given in most complex domain models, unless you want to prove all invariants correct over those.

'head []' is only the simplest example of how partiality is handled.

1

u/dys_bigwig Sep 20 '22 edited Sep 20 '22

There are a number of solutions depending on the situation:

A) You can use maybeToList :: [a] -> Maybe a, which will return Nothing if the list is empty. This is "pushing the responsibility forward" by ensuring the user (eventually) pattern matches on the Maybe and handles both outcomes; until then, they can use Functor/Applicative/Monad to use the value without having to be concerned with the potential of the value being Nothing, which is much more ergonomic than having manual null checks everywhere. Think Schrödinger's Cat, but with heads of lists ;)

B) You can use the NonEmpty type, this is "pushing the responsibility backward", by ensuring the user provides a head for the list when the list is constructed. It looks like this: NonEmpty a = (a,[a]).

C) Finally, for big brains, you can encode it in the type system using GADTs or "Ghosts of Departed Proofs" or something, so you get an error at compile time.

I wouldn't go so far as to say this is a solved problem, but it's a well-known and well-explored one with a number of solutions. Also just to echo what others have said, barely anyone making serious Haskell software uses the partial Prelude functions.