120 points · by EvgeniyZh · 6y ago · 82 comments
data Ord k => Map k v = ...
This defined a data type representing an ordered map from k to v, with the additional restriction that before you can talk about such a map you had to know that the type k is orderable (has an instance of the Ord type class which defines comparison operators).This may be considered to be similar to the definition of (/) requiring that its second argument is nonzero.
This style was supplanted by leaving the data type definition 'bare' and placing the constraints on the API's functions instead:
data Map k v = ...
insert :: Ord k => k -> v -> Map k v -> Map k v
lookup :: Ord k => k -> Map k v -> Maybe v
This style is similar to instead placing the nonzero-ness constraint on the theorems which define the API of (/).In both cases there are basic engineering reasons for the switch:
- Having the constraints in the definition of terminology (Map, /) doesn't save any work, as you still need to prove those constraints to do anything or refer to it (in Haskell this meant sprinkling `Ord k =>` in the type of anything that referred to Map k v).
- In fact it results in doing more work than necessary, as you are sometimes forced to prove the constraints just to mention Map, even when what you are doing does not require them. For instance defining the empty map 'empty :: Map k v' shouldn't require you to know anything about k, because an empty tree doesn't contain any keys, let alone care about their ordering. In this case requiring Ord k in order to mention Map k v would be superfluous.
(This is by no means a standard across the community though; I'd say it's a 50/50 split)
In most other cases, putting bounds on impls leads to less repetition of those bounds and better error messages!
Another related topic is trait methods with method-level type parameters that have bounds. Those have to be repeated on every usage site so it is usually preferable to go for a design that has the type parameters in the actual trait.
Instead of:
trait Foo {
fn foo<T: Bar>(&self, bar: T)
}
do this instead: trait Foo<T> {
fn foo(&self, t: T)
}
impl<T: Bar> Foo for XYZ {
fn foo(&self, bar: T) {
}
}
One bound might seem fine in this example but once stuff needs to be Send, Sync and 'static is when it gets annoying. data TC x where
DC :: Ord x => x -> TC x -- `Ord x` exists when matching on DC constructor
ex1 :: TC x -> x -> x -> Ordering
ex1 (DC _) a b = compare a b
-- Without constructor match, no Ord instance
ex2 :: TC x -> x -> x -> Ordering
ex2 _ a b = compare a b -- ERROR!
-- This is why the above ex2 definition is an error
badUser :: x -> x -> Ordering
badUser a b = ex2 undefined a b
-- No `TC x` value also means no Ord instance even
-- though no arguments are ignored or undefined
data Proxy x = Proxy
ex2 :: Proxy (TC x) -> x -> x -> Ordering
ex2 Proxy a b = compare a b -- ERROR!If I ever divide by zero (or by something that might be zero) in my proof, I've almost certainly made a mistake. I'd rather hear about it straight away than later when I try to use some fact about the result of that division.
It also means that any type errors that don't affect the expanded template (but may still have an effect on semantics) will not be caught at all.
Interestingly enough, constructions for add, (natural) subtract and multiply work as you would expect with this infinite number without needing special handling. E.g. for all n, n + inf == inf, n - inf == 0, n * inf == inf.
Furthermore, the construction for (natural) div yields this infinite term (or at least something that behaves exactly like it) when the denominator is 0. Even more interestingly, 0/0 == inf for this system.
EDIT: Why might this be useful? Well now when you 'take n' from a list, n=inf will give you the whole list, regardless of how long (or even if it is infinite - i.e. lazy). Likewise 'drop n' will return the empty list - except with an infinite list, whereupon the calculation will fail to terminate.
EDIT: inf - inf == non-termination in this system, suggesting that not only inf - inf != 0, but it != inf either, and in fact it is something unreachable (in this system) (note the correspondence between 'subtract' and 'drop').
What I found interesting about the Scott encoding was that natural infinity was trivial to define, and arises directly from a straightforward construction of the div function (for naturals).
The encoding is as follows (\x indicates lambda abstraction for identifier x. Recursion is assumed, of course it could be made explicit with the Y combinator):
zero := \f \x n
succ := \n \f \x f n
infinite := \n succ (infinite n)
infinity := infinite zero
subn := \n \m m (\p n (\q subn q p) n) n
divn := \n \m (subn m n) (\p zero) (succ (divn (subn n m) m))
divn (succ zero) zero => infinity
EDIT: Note that infinity does not have a normal form (does not terminate), but: subn n infinity => zeroHowever I don't think any of this matters for the point the article made. The problem is not that 1:N/0:N has "nothing sensible" to return, the problem is that if you define it in the way most mathematicians do, a lot of your proofs will be littered with (inline) lemmas showing that the result of such-and-such a division is a finite natural / finite real. This is analogous the problem brought up in the article of having proofs littered with lemmas showing that the result of such-and-such a square root was real.
I would expert this to be 0 actually.
Among other things, this would have the unpleasant effect of making expressions like "0÷1" undefined, because the result could equal either zero or infinity.
mathematician here. The expression 1/0 is not "obviously" halt and catch fire. Extended real numbers (either projectively or affinely) are a well-known thing. If you see the expression 1/0 or 1/f(x) where f(x) may take the 0 value you do not halt and catch fire; you assume that the operations are taking place in a place where they make sense. A very common usage is when f(x)=0 for a zero-measure set of x, and then 1/f(x) has dirac masses at these points (weighted by the absolute value of the derivative of f).
On the other hand, I agree that "type theory" would sound like a ridiculously unnecessary abstraction to most of us.
(You may then do a separate proof in the case that x = 0, if you want to prove something for all x including 0.)
Relatedly, there is value to non-local error handling (i.e. unchecked exceptions), catching logical errors at a local level makes little sense.
This places the burden on the person using the function to prove that x isn't 0, but that's the price you have to pay to have a proper multiplicative inverse.
Alternatively, defining f(0) to be infinity (a projectively extended real number) also allows f to be continuous.
Another possibility is to define f(0) to be some kind of "bottom" value. See the following tweets by Andrej Bauer: https://twitter.com/andrejbauer/status/1268860981943439361
Continuity is important because without it we lose computability. Every computable function is continuous (in an appropriate sense).
But, I don't think what you said is quite right, either. If you define f(x) = 1/x over the non-zero reals, then the range does have the same type as the domain- you can't get zero out of the function, so the range is also the non-zero reals.
Not quite. The extended reals are ℝ + {inf, -inf}. This has the problem that 1/x approaches inf from the right and -inf from the left.
As ogogmad notes, in order to define a value for 1/x at 0, you need the projectively extended reals.
1. The article's way: "R^2->R", but garbage value for 0 in the second argument.
2. What you propose: "R^2->Maybe R"
3. The mathematician's dependent-type-theoretic way "R * (x:R, proof that x!=0) -> R",
4. the conventional way "R * (R\{0}) -> R".
They have their advantages and disadvantages. The first is useful in proof verification since it simplifies most proofs, from which perspective this garbage value of 0 is actually well-behaved, and doesn't need to be handled as a special case. But you allow seemingly nonsense theorems when you forget to condition (x>0).
What you propose is similar, except that you are forced to reason about whether the output value is valid.
3 and 4 are tedious, since you always need to prove that the inputs are nonzero. 4 is more tedious since you have merely shifted the problem of handling the zero case into proving properties about the canonical embedding "R->R\{0}" (which must still have a garbage value for 0). On the upside, these functions surject into R.
Such as what? I’ve only spent a few hours with lean, but I’m fairly sure that any attempt to prove something silly would fail because it would catch the weird behavior of 0.
For example. If you tried to use a/a = 1 as the article mentions, you’d be unable to prove it without adding the condition that a != 0, and you’d be unable to use it further on without that condition in place.
“There exists a real number r such that 1/r = 0.”
If you try to translate this theorem into maths, you will run into trouble at some point. At which point exactly depends on how you want to make things precise... which is exactly what mathematicians avoid when talking about division in fields.
Or assume it. This is what you have to do in real life anyway. If you can't assume the inputs are nonzero you have to prove it. Otherwise the proof doesn't work.
(n : Nat) -> (m : Nat) -> Nonzero m -> n / m * m = n
as in you do not need to make your laws hold true for every possible input of / which is why it does not break regular mathematics.In mathematics functions have domains and codomains. Two functions are equal if their domains are equal, their codomains are equal, and for all the values in the domain they return the same values in the codomain.
A mathematician who doesn't know anything about type theory, but hears Lean is good at formalizing math, will expect the division function to have the domain R x (R\{0}). Modifying the domain to be R x R and returning a garbage value for the added points is not a good solution. Maybe it works "in real life", but you always need to carry with you an invisible asterisk and footnote that Lean did the right thing only assuming you asked the right question.
Again, being humble (my Lean experience is about one hour in total, spread across several sessions), I think it would be better to invest a bit more time upfront and always define properly the domain of the function used, rather than introduce edge cases that can bite you in the back twenty five theorems down the road.
[1] https://math.stackexchange.com/questions/334393/how-does-typ...
This choice works fine when using type theory in theorem provers, but would be unacceptable if we did it in programming languages that use type theory (or would that be called “type practice” ;-)?)
In Haskell, for example, 1/0 returns Infinity.
1 / 0 :: Double
evaluates to Infinity. 1 / 0 :: Rational
throws a runtime exception. A division by zero producing zero would be perfectly sensible in Haskell, and perhaps even desired if you are totally averse to runtime errors. The Pony language infamously does this.Programming languages such as Haskell and Java are not based on type theory. They have type systems. Haskell's type system is much closer to type theory than that of Java, but it's still quite crippled compared to what type theorists study.
It is of course possible to define things in type theory such that 1/0 = Infinity or something else, but that is not the norm.
I can understand that it makes sense for proof assistants. As the post shows, proof assistants don't allow you to misuse that anywhere else.
(But as a sidenote: couldn't you fix this with dependent types somehow?)
I still think it would be wrong for a regular programming language. Afaik, the Pony language does this too, but that is a general-purpose programming language that does not check your logic, and I am very wary of something like that. People might type up some algorithms, or even just try to compute an average, and the system absolutely should yell at you if you try to divide by zero.
For what it's worth, I'm willing to argue that Pony is making a strongly motivated choice by making x/0 return 0 by default with respect to their specific error-handling model. In general, I don't think it's as much of a problem as you might imagine. The average function is a perfect example: if I naïvely implement it in such a language, then it would mean… that average([]) returns 0. That doesn't seem terribly bad to me.
But I still think in other situations I'd want to be yelled at for trying to divide by zero. E.g. imagine I'm trying to compute the slope of a secant between two points. If both points are the same, I'd like the compiler to yell at me (the problem either makes no sense here, indicating a problem somewhere else in my code, or that I should instead compute the derivative) - in most cases, 0 would be the wrong answer. I think the issue here is that with division by zero you lose continuity (unless you use +Inf) which can contradict intuition.
I'm not saying it doesn't work for Pony, maybe it does, but I don't think I would feel comfortable with that behaviour.
Silent wrapping around on overflow is arguably even worse, that I could definitely see leading to logic errors.
Any choice of behavior for x/0 will be wrong in some context, and the question is really about how much help you want from the computer (both from the type system in trying to prevent/model division by 0 and at runtime via errors, via choosing a value for the division, etc).
quoting from the post:
> the way I had set things up, every time I used the [sqrt] symbol I had to supply a proof that what I was taking the square root of was non-negative.
"supplying a proof" is how you do it in dependently-typed systems afaik. the author tried it, and it was inconvenient
Most proof assistants, including Lean, are built on dependent type theory.
The Metamath Proof Explorer defines "/" so it only has a value if the denominator is a nonzero complex number: http://us.metamath.org/mpeuni/df-div.html
You can argue if that is better, but that is a possible choice.