У чому саме полягає смислова різниця між множиною та типом?


33

EDIT: Зараз я задав подібне запитання про різницю між категоріями та наборами.

Кожен раз, коли я читаю про теорію типів (яка, правда, досить неформальна), я не можу реально зрозуміти, чим вона відрізняється від теорії множин, конкретно .

Я розумію, що між висловлюванням "х належить множина X" і "x належить до типу X" існує концептуальна різниця, оскільки інтуїтивно набір - це лише сукупність об'єктів, тоді як тип має певні "властивості". Тим не менш, набори часто визначаються і за властивостями, і якщо вони є, то у мене виникають проблеми з розумінням того, як ця різниця має значення в будь-якому випадку.

Таким чином , в найбільш конкретному чином це можливо, що саме це означає , про х , щоб сказати , що вона має тип Т , по порівнянні з кажучи , що він є елементом множини S ?

(Ви можете вибрати будь-який тип і набір, який робить порівняння найбільш зрозумілим).


Який контекст, у якому ви використовуєте / чуєте слово "тип"? Це, як підказує ваше ім’я, мови програмування? Тому що я думаю, що відповіді нижче припускають інше.
einpoklum - відновити Моніку

@einpoklum, я не на 100% впевнений, як описати, що таке "контекст", але в основному щось подібне: я намагаюся зрозуміти роль типів у математиці. По суті, множини (як я бачу) мають два контексти: по-перше, вони використовуються як колекції предметів для щоденної математики. По-друге, це об'єкти в теорії аксіоматичних множин, де вони в основному використовуються як дуже дивний, але корисний інструмент для говорити про математику в логіці першого порядку, дозволяючи множинам відповідати функціям і числам тощо. Мене в основному цікавить співвідношення "встановити" в першому сенсі і "типу".
користувач56834

Роль яких типів? Типи, які ви бачите в математичних роботах / підручниках, або типи змінних в комп'ютерних програмах?
einpoklum - відновити Моніку

1
@einpoklum, це питання стосується тих, які є в математичних роботах. (Хоча насправді мені також цікаво знати принципову різницю між типами математики та типами мов програмування, якщо такі є. Але це питання не стосується цього питання).
user56834

Відповіді:


29

Щоб зрозуміти різницю між множинами та типами, треба повернутися до передматематичних ідей "колекція" та "побудова", і побачити, як множини та типи їх математизують .

Існує спектр можливостей щодо математики. Дві з них:

  1. Ми розглядаємо математику як діяльність, в якій математичні об’єкти будуються за деякими правилами (мислимо геометрію як діяльність з побудови точок, ліній та кіл за допомогою лінійки та циркуля). Таким чином, математичні об'єкти організовуються відповідно до того, як вони побудовані , і існують різні типи побудови. Математичний об’єкт завжди будується якимось унікальним способом, що визначає його унікальний тип.

  2. Ми думаємо про математику як про величезний всесвіт, повний попередніх математичних об'єктів (подумайте про геометричну площину, як дано). Ми виявляємо, аналізуємо і думаємо про ці об’єкти (ми спостерігаємо, що в площині є точки, лінії та кола). Ми збираємо їх у комплект . Зазвичай ми збираємо елементи, які мають щось спільне (наприклад, всі лінії, що проходять через дану точку), але в принципі набір може містити довільний вибір об'єктів. Набір визначається його елементами, і лише його елементами. Математичний об’єкт може належати до багатьох наборів.

Ми не кажемо, що наведені вище можливості є єдиними двома, або що будь-яка з них повністю описує, що таке математика. Тим не менш, кожен з них може послужити корисним відправною точкою для загальної математичної теорії, яка корисно описує широкий спектр математичних занять.

Природно взяти типу і уявити собі сукупність всіх речей , які ми можемо побудувати , використовуючи правила T . Це розширення з T , і це НЕ Т сама. Наприклад, тут є два типи, які мають різні правила будівництва, але вони мають однакове розширення:TTT T

  1. Тип пар де n побудовано як натуральне число, а p побудований як доказ, що демонструє, що n - парне число, що перевищує 3 .(n,p)npn3

  2. Тип пар де m побудований як натуральне число, а q побудований як доказ, що демонструє, що m - непарний простір менший за 2 .(m,q)mqm2

Так, це нерозумні тривіальні приклади, але справа в тому, що обидва типи нічого не мають у своєму розширенні, але вони мають різні правила побудови. На відміну від цього, множини а { m Nm  - непарний простір, менший ніж  2 }, є рівними, оскільки вони мають однакові елементи.

{nNn is an even prime larger than 3}
{mNm is an odd prime smaller than 2}

Зауважимо, що теорія типів не стосується синтаксису. Це математична теорія конструкцій, як і теорія множин - це математична теорія колекцій. Так буває, що звичайні виклади теорії типів підкреслюють синтаксис, і, отже, люди в кінцевому підсумку думають, що теорія типу є синтаксисом. Це не так. Плутати математичний об’єкт (конструкцію) з синтаксичним виразом, який представляє його (термін колишній) - це основна помилка категорії, яка спантеличує логіків давно, але вже не.


1
Красиво, дякую! Не могли б ви уточнити одну деталь? коли ви перераховуєте два типи, розширення яких обоє порожні, ви говорите, що "тип, елементи якого ...". Чисто для моєї ясності, це 100% правильний спосіб сказати це? Ви сказали в попередньому реченні, що тип не є колекцією, тому здається, що він не може мати "елементів" (які я асоціюю з наборами). По суті, так, як ви це написали зараз, це як би ви визначаєте Тип відповідно до набору, який є його розширенням. Якщо ви цього не мали наміру, чи могли б ви перефразувати їх точніше, щоб зафіксувати їх ідею як види?
користувач56834

Розширення такого типу є дуже корисною концепцією, і , оскільки вона є свого роду колекції, можна сказати , «елемент розширення типу». Це громіздко, тому його часто скорочують до просто "елемента типу". Я видалив фразу, щоб зменшити можливість плутанини, але будьте обережні, це звичайна термінологія.
Андрій Бауер

Дякую, це уточнює. Отже, щоб продовжити, чи правильно сказати наступне? Сказати, що об’єкт "типу T" означає те саме, що об'єкт є "елементом розширення T", так що існує природне викидання від типів до множин. Але зворотне не має значення, оскільки будь-який набір може бути побудований декількома способами. По суті, різниця між множиною і типом не важлива з точки зору конкретного об'єкта , в тому сенсі, що x : T і x X T (де X T є розширенням T ) дають нам точно таку ж інформацію про x . Однак,xx:TxXTXTTx
user56834

Різниця актуальна, коли ми хочемо поговорити про типи та множини, їх властивості та відношення. Таким чином, іншими словами, інформація, яку ми втрачаємо, коли ми говоримо а не x : T , не говорить нам нічого релевантного про x , але те ж саме не може бути справедливим, якщо ми, наприклад, хочемо поговорити про підмножину підмножини чи тип- підтипові відносини? Це правильно? xXTx:Tx
користувач56834

4
Так, дивується, де ці книги. Хтось повинен їх написати.
Андрій Бауер

11

Для початку набори та типи навіть не на одній арені. Набори - це об'єкти теорії першого порядку, наприклад, теорія множин ZFC. Хоча типи схожі на зарослі сорти. Говорячи по - іншому, теорії множин є теорія першого порядку в логіці першого порядку. Теорія типів - це розширення самої логіки. Наприклад, теорія типу Мартіна-Лефа не представлена ​​як теорія першого порядку в логіці першого порядку. Не так часто говорити про набори та типи одночасно.

Як дискретні стани ящірок, типи (і сорти) виконують синтаксичну функцію. Сорт / тип поводиться як синтаксична категорія . Це дає нам знати, які вирази добре сформовані. Для простого прикладу з використанням сортів, скажімо, ми описали теорію векторних просторів над довільним полем як 2-сортовану теорію. У нас є свого роду для скалярів, , і свого роду для векторів, V . Серед багатьох інших речей, ми повинні були б операція для масштабування: и з л е : S × VV . Це дає нам знати, що s c a l e ( s c a l eSVscale:S×VVscale(scale(s,v),v) - просто не добре сформований термін. У контексті теоретичного типу, вираз виду вимагає п мати тип X Y для деяких типів X і Y . Якщо f не має типу функції, то f ( x ) просто не є добре сформованим виразом. Незалежно від того, чи є якийсь вираз, чи має якийсь тип, це мета-логічне твердження. Немає сенсу писати щось на зразок: ( x : X )f(x)fXYХYff(x) . По-перше, x : X(x:X)y=3x:X просто не є формулою, по-друге, це навіть не має концептуальної сенсу, оскільки сорти / типи - це те, що дозволяє нам знати, які формули добре сформовані. Ми розглядаємо лише значення істинності добре сформованих формул, тому до того часу, коли ми розглядаємо, чи дотримується якась формула, ми краще вже знаємо, що вона добре сформована!

У теорії множин, а особливо у ZFC, єдиним нелогічним символом взагалі є символ відношення для встановленого членства, . Отже x y - це добре сформована формула зі значенням істини. Немає ніяких термінів, крім змінних. Усі звичні позначення теорії множин є певним розширенням до цього. Наприклад, формула на зразок f ( x ) = y часто вважається скороченою для ( x , y ) f, яка сама може вважатися скороченою для p . p f p = ( ,xyf(x)=y(x,y)f , якасобою скороченур . p p.pfp=(x,y)

p.pf(z.zp[z=x(w.wzw=y)])
fπ(7)=3π справжнє число є цілком законним і значущим (а можливо, навіть істинним) заданим теоретичним виразом. В основному, все, що ви пишете, що аналізує теорію множин, може надати деяке значення. Це може бути мати цілком хибне значення, але воно має його. Набори - це також "першокласні" об'єкти в теорії множин. (Вони краще бути такими, якими вони є
f(x)={N,if x=17,if x=QxRR,if x=(Z,N)
is a completely legitimate function in set theory. There is nothing even remotely analogous to this in type theory. The closest would be to use codes for a Tarskian universe. Sets are the objects of set theory; types are not the object of type theory.

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.


1
It is false that types are only syntactic entities.
Andrej Bauer

1
This is very helpful, but one main point in your answer bugs me. It seems to me that it is a mistake (which many people make, or alternatively it is not a mistake and I'm wrong), to say that "a set is not a collection of things". I would say that a set IS a collection of things. That is the most basic essential property of a set. In fact, how would we possibly know that e.g. ZFC are the right axioms to choose (rather than completely arbitrary formulas), without being able to tell that they are true given that sets are collections of objects? Of course, I understand that ...
user56834

Axiomatic set theory treats sets as objects, and as just a symbol, because axiomatic set theory is not a mathematical structure in the mathematical logic sense.
user56834

1
@Programmer2134 To answer that, we would have to get into the semantic meaning of the word "collection." We can't be sure they are "right" unless you take the time to precisely define what "right" means. However, what we can say is that "set" is the result of over a hundred years of mathematicians beating on the concept of a collection, seeking a consistent system which matches the intuitive concept of a collection. To achieve that consistency, they had to make decisions. For example, sets aren't the only collection in mathematics. A "class" also describes a collection.
Cort Ammon - Reinstate Monica

1
@AndrejBauer I'm taking a (mostly) non-philosophical stance and not trying to explain what types "really" are but more how they're used. (I say "serves as" and "behaves as" at the beginning but I did slip into an "is" at the end.) There is a risk of thinking that a variable x being of type T means that the only "values" that x can "take" are the (presumably closed) terms of type T. This isn't true and is not implied by anything I say above. I agree that you can see types as more than syntactic entities, but I think the different syntactic role types play makes a clear contrast to sets.
Derek Elkins

9

In practice, claiming that x 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:

3+(78)5:Nat,
and an example of being member of a set:
3{nNx,y,zN+(xn+ynzn)}

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 the 3 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.


3
Type checking doesn't need to be decidable (though it is certainly desirable). NuPRL, for instance, does require the user to provide a proof that a term inhabits a type.
Derek Elkins

3
Thank you. Things are becoming more clear. Heres what I'm wondering still: isn't there a semantic element to type theory and a syntactic element to set theory? For example, we can instead of seeing your "3..." statement as a semantic statement, see it as a proposition in axiomatic set theory, no? Also, doesn't the type "Nat" have a semantic meaning, namely that whatever precedes it is a natural number? So it still confuses me to say rhat sets are semantic and types syntactic properties.
user56834

1
@DerekElkins I'm not familiar with NuPRL, but e.g. the proof assistant Coq most certainly does type checking by itself (i.e, is the provided term of the 'type of my theorem'). How does NuPRL verify the proof if the user has to 'prove' the fact that a term of a certain type? (in other words, this sounds like NuPRL doesn't use the Curry-Howard correspondence, so what does it use?)
Discrete lizard

1
@Discretelizard I'm not saying NuPRL is typical. It is definitely the usual case for type checking to be decidable. I highly recommend becoming familiar with it just because it takes a fairly different path. NuPRL is a Curry-style rather than Church-style calculus which makes it more of a type refinement system. At any rate, instead of just writing terms (or tactics that produce terms), you have essentially an LCF-style proof system for typing derivations themselves. Arguably, the derivations are what's important, and it's a bit of a "fluke" that we can infer them from terms.
Derek Elkins

3
I elaborated in my answer why it is detrimental to think of type theory as "syntactic". Your first sentence is the offeding one, when you say that "inhabiting a type is a syntactic property". There's as much truth in that as in saying that "being an element of a set is to stand on the left of the symbol ".
Andrej Bauer

4

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 booleans B={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 whether a=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:BS and ιN:NS, 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.


You are probably thinking of one specific kind of set theory (something along a single-sorted theory a la ZFC). However, there are other kinds of set theory which require lots of checking that it makes sense. And the way set theory is used in practice is much closer to these other set theories. Do you think a student could ask "Is R an element of sin(2)?" without being scolded? The distinction between type theory and set theory is not in the formalism, it's in the meaning.
Andrej Bauer

@AndrejBauer Right. Would you agree that this answer gives a differences between single-sorted theories (including most set theories, or at least the most common ones), and multi-sorted theories (including all (?) type theories)?
xavierm02

Even in a single-sorted theory you have to distinguish terms from formulas...
Andrej Bauer

@AndrejBauer I don't understand your second comment.
xavierm02

A single-sorted first-order theory has two syntactic categories: logical formulas and terms. One has to make sure they're not mixed up, or else you could end up writing "(xX.ϕ(x))N".
Andrej Bauer
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.