Введение
Формальная система в математической логике.
Лямбда-исчисление простого типа, являющееся формой теории типов, представляет собой типизированную интерпретацию лямбда-исчисления с единственным конструктором типа, формирующим типы функций. Это канонический и наиболее простой пример типизированного лямбда-исчисления. Лямбда-исчисление простого типа было первоначально введено Алонзо Черчем в 1940 году как попытка избежать парадоксального использования нетипизированного лямбда-исчисления. Его лямбда-исчисление, как формальный язык, основанный на символических выражениях, состояло из счетно бесконечного ряда аксиом и переменных, а также из конечного набора примитивных символов и конечного набора правил I–VI. Этот конечный набор правил включал правило V modus ponens, а также правила IV и VI для подстановки и обобщения соответственно. (1) (2) (3) (4)
The simply typed lambda calculus , a form
of type theory, is a typed interpretation of the lambda calculus with only one type constructor that builds function types. It is the canonical and simplest example of a typed lambda calculus. The simply typed lambda calculus was originally introduced by Alonzo Church in 1940 as an attempt to avoid paradoxical use of the untyped lambda calculus. his lambda calculus, as a formal language based on symbolic expressions, consisted of a denumerably infinite series of axioms and variables, but also a finite set of primitive symbols, and also, a finite set of rules I to VI. This finite set of rules included rule V modus ponens as well as IV and VI for substitution and generalization respectively. (1) (2) (3) (4)
In words,
If has type in the context, then has type Term constants have the appropriate base types. If, in a certain context with having type , has type , then, in the same context without , has type If, in a certain context, has type , and has type , then has type
Examples of closed terms, i. e. terms typable in the empty context, are:
For every type , a term (identity function/I combinator),
For types , a term (the K combinator), and
For types , a term (the S combinator). These are the typed lambda calculus representations of the basic combinators of combinatory logic. Each type is assigned an order, a number For base types, ; for function types, That is, the order of a type measures the depth of the most left nested arrow. Hence:
Иными словами, если имеет тип в данном контексте, то имеет тип . Терминные константы имеют соответствующие базовые типы. Если в определенном контексте, где имеет тип , имеет тип , то в том же контексте без имеет тип . Если в определенном контексте имеет тип , и имеет тип , то имеет тип .
The simply typed lambda calculus , a form
of type theory, is a typed interpretation of the lambda calculus with only one type constructor that builds function types. It is the canonical and simplest example of a typed lambda calculus. The simply typed lambda calculus was originally introduced by Alonzo Church in 1940 as an attempt to avoid paradoxical use of the untyped lambda calculus. his lambda calculus, as a formal language based on symbolic expressions, consisted of a denumerably infinite series of axioms and variables, but also a finite set of primitive symbols, and also, a finite set of rules I to VI. This finite set of rules included rule V modus ponens as well as IV and VI for substitution and generalization respectively. (1) (2) (3) (4)
In words,
If has type in the context, then has type Term constants have the appropriate base types. If, in a certain context with having type , has type , then, in the same context without , has type If, in a certain context, has type , and has type , then has type
Examples of closed terms, i. e. terms typable in the empty context, are:
For every type , a term (identity function/I combinator),
For types , a term (the K combinator), and
For types , a term (the S combinator). These are the typed lambda calculus representations of the basic combinators of combinatory logic. Each type is assigned an order, a number For base types, ; for function types, That is, the order of a type measures the depth of the most left nested arrow. Hence:
Примеры закрытых термов, то есть термов, типизируемых в пустом контексте:
Для каждого типа , терм (комбинатор тождества/I-комбинатор),
Для типов , терм (K-комбинатор), и
Для типов , терм (S-комбинатор). Это типизированные представления лямбда-исчисления основных комбинаторов комбинаторной логики. Каждому типу присваивается порядок – число. Для базовых типов порядок равен 0; для функциональных типов порядок равен 1 плюс порядок типа аргумента. То есть, порядок типа измеряет глубину наиболее левой вложенной стрелки. Следовательно:
The simply typed lambda calculus , a form
of type theory, is a typed interpretation of the lambda calculus with only one type constructor that builds function types. It is the canonical and simplest example of a typed lambda calculus. The simply typed lambda calculus was originally introduced by Alonzo Church in 1940 as an attempt to avoid paradoxical use of the untyped lambda calculus. his lambda calculus, as a formal language based on symbolic expressions, consisted of a denumerably infinite series of axioms and variables, but also a finite set of primitive symbols, and also, a finite set of rules I to VI. This finite set of rules included rule V modus ponens as well as IV and VI for substitution and generalization respectively. (1) (2) (3) (4)
In words,
If has type in the context, then has type Term constants have the appropriate base types. If, in a certain context with having type , has type , then, in the same context without , has type If, in a certain context, has type , and has type , then has type
Examples of closed terms, i. e. terms typable in the empty context, are:
For every type , a term (identity function/I combinator),
For types , a term (the K combinator), and
For types , a term (the S combinator). These are the typed lambda calculus representations of the basic combinators of combinatory logic. Each type is assigned an order, a number For base types, ; for function types, That is, the order of a type measures the depth of the most left nested arrow. Hence:
Внутренние и внешние интерпретации
В целом, существует два различных подхода к приданию смысла просто типизированному лямбда-исчислению, а также типизированным языкам в более широком смысле, которые называют внутренним и внешним, онтологическим и семантическим, или стилем Черча и стилем Карри. Внутренняя семантика приписывает смысл только корректно типизированным термам, или, точнее, непосредственно типовым выводкам. Это приводит к тому, что термы, различающиеся только типовыми аннотациями, тем не менее могут иметь разные значения. Например, терм тождества для целых чисел и терм тождества для булевых значений могут означать разные вещи. (Классические интерпретации – это функция тождества на целых числах и функция тождества на булевых значениях.) В отличие от этого, внешняя семантика приписывает смысл термам независимо от их типизации, как если бы они интерпретировались в нетипизированном языке. С этой точки зрения, и означают одно и то же (то есть то же самое, что и ). Различие между внутренней и внешней семантикой иногда связывают с наличием или отсутствием аннотаций у лямбда-абстракций, но строго говоря, такое употребление неточно. Можно определить внешнюю семантику для аннотированных термов, просто игнорируя типы (то есть посредством стирания типов), как и можно задать внутреннюю семантику для неаннотированных термов, когда типы могут быть выведены из контекста (то есть посредством вывода типов). Существенное различие между внутренним и внешним подходами заключается в том, рассматриваются ли правила типизации как определяющие язык, или как формализм для проверки свойств более примитивного базового языка. Большинство различных семантических интерпретаций, обсуждаемых ниже, можно рассматривать либо с внутренней, либо с внешней точки зрения.
are the identity function on integers and the identity function on boolean values.) In contrast, an extrinsic semantics assigns meaning to terms regardless of typing, as they would be interpreted in an untyped language. In this view, and mean the same thing (i. e., the same thing as ). The distinction between intrinsic and extrinsic semantics is sometimes associated with the presence or absence of annotations on lambda abstractions, but strictly speaking this usage is imprecise. It is possible to define an extrinsic semantics on annotated terms simply by ignoring the types (i. e., through type erasure), as it is possible to give an intrinsic semantics on unannotated terms when the types can be deduced from context (i. e., through type inference). The essential difference between intrinsic and extrinsic approaches is just whether the typing rules are viewed as defining the language, or as a formalism for verifying properties of a more primitive underlying language. Most of the different semantic interpretations discussed below can be seen through either an intrinsic or extrinsic perspective.
Операционная семантика
Аналогичным образом, операционная семантика просто типизированного лямбда-исчисления может быть определена так же, как и для нетипизированного лямбда-исчисления, используя передачу по имени, передачу по значению или другие стратегии вычисления. Как и для любого типизированного языка, типобезопасность является фундаментальным свойством всех этих стратегий вычисления. Кроме того, свойство сильной нормализации, описанное ниже, подразумевает, что любая стратегия вычисления завершится для всех просто типизированных термов. Чисто семантическое доказательство нормализации (см. нормализацию посредством вычисления) было представлено Бергером и Швихтенбергом в 1991 году. Мы можем кодировать натуральные числа с помощью термов типа (числа Черча). Швихтенберг показал в 1975 году, что именно расширенные полиномы представимы как функции над числами Черча.