РЕДАКТИРОВАТЬ: я теперь задавал аналогичный вопрос о разнице между категориями и сетами.
Каждый раз, когда я читаю о теории типов (которая, по общему признанию, довольно неформальна), я не могу понять, чем она конкретно отличается от теории множеств .
Я понимаю, что существует концептуальная разница между высказыванием «x принадлежит множеству X» и «x имеет тип X», потому что интуитивно, набор - это просто набор объектов, в то время как тип имеет определенные «свойства». Тем не менее, наборы часто определяются также в соответствии со свойствами, и если они есть, то у меня возникают проблемы с пониманием того, как это различие имеет какое-либо значение.
Таким образом, самым конкретным возможным способом, что именно означает, что говорит, что он имеет тип , по сравнению с тем, что он является элементом в множестве ?
(Вы можете выбрать любой тип и набор, который делает сравнение наиболее понятным).
источник
Ответы:
Чтобы понять разницу между подходами и типами, из них должен вернуться к предварительно -mathematical идеи «коллекции» и «строительство», и посмотреть , как наборы и типы математизировать их.
Существует целый спектр возможностей того, что такое математика. Два из них:
Мы думаем о математике как о деятельности, в которой математические объекты строятся по некоторым правилам (под геометрией понимают деятельность по построению точек, линий и окружностей с помощью линейки и компаса). Таким образом, математические объекты организованы в соответствии с тем, как они построены , и существуют различные типы построения. Математический объект всегда строится каким-то уникальным способом, который определяет его уникальный тип.
Мы думаем о математике как о огромной вселенной, полной уже существующих математических объектов (представьте себе геометрическую плоскость как заданную). Мы обнаруживаем, анализируем и думаем об этих объектах (мы видим, что на плоскости есть точки, линии и круги). Мы собираем их в набор . Обычно мы собираем элементы, которые имеют что-то общее (например, все линии, проходящие через заданную точку), но в принципе набор может содержать произвольный набор объектов. Множество определяется его элементами и только его элементами. Математический объект может принадлежать многим наборам.
Мы не говорим, что вышеуказанные возможности являются единственными двумя, или что любой из них полностью описывает, что такое математика. Тем не менее, каждый вид может служить полезной отправной точкой для общей математической теории, которая полезно описывает широкий спектр математических действий.
Естественно взять типа и представить себе совокупность всех вещей , которые мы можем построить , используя правила T . Это расширение из T , и это не Т сама. Например, вот два типа, которые имеют разные правила построения, но имеют одинаковое расширение:T T T T
The type of pairs(n,p) where n is constructed as a natural number, and p is constructed as a proof demonstrating that n is an even prime number larger than 3 .
The type of pairs(m,q) where m is constructed as a natural number, and q is constructed as a proof demonstrating that m is an odd prime smaller than 2 .
Yes, these are silly trivial examples, but the point stands: both types have nothing in their extension, but they have different rules of construction. In contrast, the sets
Note that type theory is not about syntax. It is a mathematical theory of constructions, just like set theory is a mathematical theory of collections. It just so happens that the usual presentations of type theory emphasize syntax, and consequently people end up thinking type theory is syntax. This is not the case. To confuse a mathematical object (construction) with a syntactic expression that represents it (a term former) is a basic category mistake that has puzzled logicians for a long time, but not anymore.
источник
To start, sets and types aren't even in the same arena. Sets are the objects of a first-order theory, such as ZFC set theory. While types are like overgrown sorts. To put it a different way, a set theory is a first-order theory within first-order logic. A type theory is an extension of logic itself. Martin-Löf Type Theory, for example, is not presented as a first-order theory within first-order logic. It's not that common to talk about sets and types at the same time.
In set theory, and particularly ZFC, the only non-logical symbol at all is the relation symbol for set membership,∈ . So x∈y is a well-formed formula with a truth value. There are no terms other than variables. All the usual notation of set theory is a definitional extension to this. For example, a formula like f(x)=y is often taken to be shorthand for (x,y)∈f which itself may be taken as shorthand for ∃p.p∈f∧p=(x,y) which is shorthand for
A type is not a collection of things (neither is a set for that matter...), and it is not defined by a property. A type is a syntactic category that lets you know what operations are applicable to terms of that type and which expressions are well-formed. From a propositions-as-types perspective, what types are classifying are the valid proofs of the proposition to which the type corresponds. That is, the well-formed (i.e. well-typed) terms of a given type correspond to the valid proofs (which are also syntactic objects) of the corresponding proposition. Nothing like this is happening in set theory.
Set theory and type theory are really not anything alike.
источник
In practice, claiming thatx being of type T usually is used to describe syntax, while claiming that x is in set S is usually used to indicate a semantic property. I will give some examples to clarify this difference in usage of types and sets. For the difference in what types and sets actually are, I refer to Andrej Bauer's answer.
An example
To clarify this distinction, I will use the example given in Herman Geuvers' lecture notes. First, we look at an example of inhabiting a type:
The main difference here is that to test whether the first expression is a natural number, we don't have to compute some semantic meaning, we merely have to 'read off' the fact that all literals are of type Nat and that all operators are closed on the type Nat.
However, for the second example of the set, we have to determine the semantic meaning of the3 in the context of the set. For this particular set, this is quite hard: the membership of 3 for this set is equivalent to proving Fermat's last theorem! Do note that, as stated in the notes, the distinction between syntax and semantics cannot always be drawn that clearly. (and you might even argue that even this example is unclear, as Programmer2134 mentions in the comments)
Algorithms vs Proofs
To summarize, types are often used for 'simple' claims on the syntax of some expression, such that membership of a type can be checked by an algorithm, while to test membership of a set, we would in usually require a proof.
To see why this distinction is useful, consider a compiler of a typed programming language. If this compiler has to create a formal proof to 'check types', the compiler is asked to do an almost impossible task (automated theorem proving is, in general, hard). If on the other hand the compiler can simply run an (efficient) algorithm to check the types, then it can realistically perform the task.
A motivation for a strict(er) interpretation
There are multiple interpretations of the semantic meaning of sets and types. While under the distinction made here extensional types and types with undecidable type-checking (such as those used in NuPRL, as mentioned in the comments) would not be 'types', others are of course free to call them as such (just as free as they are as to call them something else, as long as their definitions fit).
However, we (Herman Geuvers and I), prefer to not throw this interpretation out of the window, for which I (not Herman, although he might agree) have the following motivation:
First of all, the intention of this interpretation isn't that far from that of Andrej Bauer. The intention of a syntax is usually to describe how to construct something and having an algorithm to actually construct it is generally useful. Furthermore, the features of a set are usually only needed when we want a semantic description, for which undecidability is allowed.
So, the advantage of our more stricter description is to keep the separation simpler, to get a distinction more directly related to common practical usage. This works well, as long as you don't need or want to loosen your usage, as you would for, e.g. NuPRL.
источник
I believe that one of the most concrete differences about sets and types is the difference in the way the "things" in your mind are encoded into the formal language.
Both sets and types allow you to speak about things, and collections of things. The main difference is that with sets, you can ask any question you want about things and it will maybe be true, maybe not; while with types, you first have to prove that the question makes sense.
For example, if you have booleansB={true,false} and natural numbers N={0,1,…} , with types, you can not ask if true=1 which you can with sets.
One way to interpret this is that with sets, everything is encoded into a single collection: the collection of all sets.0 is encoded as [0]={} , n+1 is encoded as [n+1]={[n]}∪[n] and true and false can be encoded by any two distinct sets. So that it actually makes sense to ask if true=1 , as it can be understood as asking if "the encoding chosen for true is the same as the encoding chosen for 1 ". But the answer to this question could change if we chose another encoding: it is about the encodings and not really about the things.
You can then think of types as describing the encoding of the things inside it. With types, to ask the question of whethera=b , you first have to show that a and b have the same type, i.e. that they were encoded in the same way, which prohibits questions such as true=1 . You could still want to have a big type S in which both B and N could be encoded, and then given two encodings ιB:B→S and ιN:N→S , you could ask whether ιB(true)=ιN(1) but the fact that this question depends on the encodings (and the choice of encodings) is now explicit.
Note that in those cases, whether the question made sense was actually easy to see but it could be much harder as in, for example,(ifvery_hard_questionthen1elsetrue)=1 .
In summary, sets let you ask any question you want, but types force you to make encodings explicit when the answer may depend on them.
источник