http___en.wikipedia.org_wiki_Formal_grammar_2.xml
1.1 2.1 2.2 3.1 3.2 4.1 5.1 6.1 7.1 8.1 9.1 10.1 11.1 12.1 13.1 15.1 15.2 16.1 17.1 18.1 18.2 19.1 20.1 21.1 22.1 23.1 23.2 24.1 25.1 27.1 28.1 29.1 30.1 31.1 32.1 33.1 35.1 36.1 36.2 37.1 38.1 38.2 38.3 39.1 40.1 42.1 43.1 44.1 44.2 46.1 47.1 48.1 50.1 51.1 52.1 53.1 53.2 54.1 55.1 56.1 57.1 58.1 59.1 60.1 61.1 61.2 63.1 65.1 66.1 67.1 68.1 69.1 69.2 70.1 70.2 71.1 71.2 71.3
Йерархия на Чомски Йерархията на Чомски е йерархия от класове формални граматики, образуващи формални езици. Въведена е през 1956 г. от американския лингвист Ноам Чомски. Освен в лингвистиката, моделът на граматиките на Чомски намира широко приложение и в други науки, като информатиката (тясно свързано със съответствията с концепции от теорията на автоматите) и биологията (Нилс К. Йерне озаглавява нобеловата си лекция „Генеративната граматика на имунната система“ и разглежда протеиновия строеж в такъв контекст). Съдържание Граматика на Чомски[редактиране | edit source] Една граматика на Чомски G има следния вид: където - T е множество от терминални символи - N е множество от нетерминални символи - → е крайно множество от правила за заместване - S е елемент от N, наречен стартов символ или аксиома. Едно правило за заместване е двойка думи (низове) от символи в T∪N: (т.е. думите са от свободната полугрупа с пораждащо множество T∪N) и може да се запише като Всяко множество → от такива правила представлява релация върху T∪N*. Ако a→b е правило за заместване, а v и w са думи от (T∪N)*, двойката - (където обозначава конкатенацията) се нарича приложение на правилото a→b и може да се запише като Релацията → (т.е. множеството от правилата) чрез приложението индуцира релация ⇒ върху T∪N*, която се нарича полугрупова (или алгебрична) обвивка. Рефлексивната транзитивна обвивка на ⇒ обозначаваме с ⇒*. Една граматика на Чомски дефинира генеративно формален език Lg: Елементи на този език са само думи, състоящи се от терминални символи, които могат да се произведат чрез приложение на правилата, започвайки от думата, съдържаща единствено аксиомата S. Освен това, всяка граматика на Чомски дефинира редуктивно формален език Lr: Този език включва всички думи, които могат да се редуцират до думата, съдържаща единствено аксиомата S, чрез приложение на правилата. За да се укаже изрично посоката на приложение, често се говори за редуктивни и генеративни граматики. За всяка редуктивна граматика съществува съответна генеративна граматика (където →T е обратната на → релация), за която важи С други думи, редуктивните и генеративните граматики са взаимно дуални. Примери[редактиране | edit source] Граматика с терминални символи {a, b}, нетерминални символи {S, A, B}, правила: - (където e обозначава празната дума) и аксиома S, дефинира генеративно езика на всички думи от вида (т.е. n пъти а, последвани от m пъти b). Следната по-проста граматика дефинира генеративно същия език: Терминални символи {a, b}, нетерминални {S}, аксиома S, правила: Типове в йерархията[редактиране | edit source] Граматиките на Чомски се класифицират по следния начин. (Дефинициите се ограничават до редуктивния случай, тъй като генеративният е напълно аналогичен.) Тип 0[редактиране | edit source] Тип 0 включва всички формални граматики. Дефинираните чрез тях езици са точно тези, които могат да бъдат разпознати от една машина на Тюринг. Тези езици се наричат също рекурсивно изброими езици. Тип 1[редактиране | edit source] Граматиките от тип 1 (контекстните граматики) са граматики, които съдържат само правила със следния вид (За множество М, М+ е съкращение на .) Такива правила се наричат контекстни (англ. context-sensitive). Граматиките от тип 1 са монотонни спрямо дължината на думата. В тях се допуска и правилото ако аксиомата S не се среща от лявата страна на нито едно от правилата. Тип 2[редактиране | edit source] Граматики от тип 2 (безконтекстните граматики) са всички граматики от тип 1, които съдържат само правила от вида Такива правила се наричат безконтекстни (англ. context-free). Тип 3[редактиране | edit source] Безконтекстни правила от вида се наричат двустранно линейни. Ако v или w се равнява на празната дума, правилата се наричат съответно ляволинейни или дяснолинейни. Правила от вида се наричат терминални. Граматики от тип 3 (регулярни граматики) са всички граматики от тип 2, които съдържат само правила, които са - терминални или ляволинейни; или - терминални или дяснолинейни Езиците на тези граматики могат да се опишат и чрез регулярни изрази. Йерархия на формалните езици[редактиране | edit source] Йерархията на граматиките определя и съответни типове формални езици. Ако за един език L съществува граматика G от тип i с L=L(G), то за този език се казва че е от тип i и се записва: Освен това важи: Т.е. всички регулярни езици са безконтекстни, всички безконтекстни езици са контекстни и всички контекстни езици са рекурсивно изброими, като нито един от типовете не е равен на друг. Абстрактни машини[редактиране | edit source] Типовете в йерархията съответстват на езиците, разпознавани от различни видове абстрактни машини: Литература[редактиране | edit source] - Chomsky N. 1956. Three models for the description of language, IRE Transactions on Information Theory, Vol. 2, стр. 113-124. - Chomsky N. 1959. On certain formal properties of grammars, Information and Control, Vol. 1, стр. 91-112. Einführung i.d. Informatik, Band 2, стр. 191-212. Berlin, Heidelberg: Springer.
1.1 2.1 2.2 2.3 3.1 3.2 4.1 4.2 4.3 4.4 4.5 5.1 5.2 5.3 6.1 7.1 8.1 9.1 10.1 11.1 12.1 13.1 14.1 15.1 15.2 15.3 15.4 15.5 15.6 15.7 15.8 16.1 19.1 19.2 19.3 19.4 19.5 19.6 20.1 21.1 22.1 23.1 24.1 25.1 27.1 27.2 27.3 28.1 29.1 29.2 30.1 31.1 32.1 33.1 34.1 34.2 35.1 36.1 37.1 38.1 39.1 44.1 44.2 45.1 46.1 47.1 48.1 48.2 48.3 48.4 48.5 49.1 50.1 50.2 50.3 51.1 54.1 54.2 55.1 56.1 56.2 56.3 57.1 58.1 58.2 59.1 60.1 60.2 61.1 62.1 63.1 64.1 64.2 65.1 66.1 66.2 67.1 67.2 68.1 68.2 68.3 69.1 70.1 71.1 72.1 73.1 74.1 74.2 74.3 74.4 75.1 75.2 75.3 76.1 76.2 76.3 77.1 77.2 77.3 78.1 79.1 80.1 81.1 81.2 81.3 81.4 82.1 83.1 84.1 85.1 86.1 87.1 88.1 89.1 89.2 90.1
Formal grammar In formal language theory, a grammar (when the context is not given, often called a formal grammar for clarity) is a set of production rules for strings in a formal language. The rules describe how to form strings from the language's alphabet that are valid according to the language's syntax. A grammar does not describe the meaning of the strings or what can be done with them in whatever context—only their form. Formal language theory, the discipline which studies formal grammars and languages, is a branch of applied mathematics. Its applications are found in theoretical computer science, theoretical linguistics, formal semantics, mathematical logic, and other areas. A formal grammar is a set of rules for rewriting strings, along with a "start symbol" from which rewriting starts. Therefore, a grammar is usually thought of as a language generator. However, it can also sometimes be used as the basis for a "recognizer"—a function in computing that determines whether a given string belongs to the language or is grammatically incorrect. To describe such recognizers, formal language theory uses separate formalisms, known as automata theory. One of the interesting results of automata theory is that it is not possible to design a recognizer for certain formal languages. Parsing is the process of recognizing an utterance (a string in natural languages) by breaking it down to a set of symbols and analyzing each one against the grammar of the language. Most languages have the meanings of their utterances structured according to their syntax—a practice known as compositional semantics. As a result, the first step to describing the meaning of an utterance in language is to break it down part by part and look at its analyzed form (known as its parse tree in computer science, and as its deep structure in generative grammar). Contents - 1 Introductory example - 2 Formal definition - 3 The Chomsky hierarchy - 4 Analytic grammars - 5 See also - 6 References - 7 External links Introductory example[edit] A grammar mainly consists of a set of rules for transforming strings. (If it only consisted of these rules, it would be a semi-Thue system.) To generate a string in the language, one begins with a string consisting of only a single start symbol. The production rules are then applied in any order, until a string that contains neither the start symbol nor designated nonterminal symbols is produced. A production rule is applied to a string by replacing one occurrence of its left-hand side in the string by its right-hand side (cf. the operation of the theoretical Turing machine). The language formed by the grammar consists of all distinct strings that can be generated in this manner. Any particular sequence of production rules on the start symbol yields a distinct string in the language. If there are multiple ways of generating the same single string, the grammar is said to be ambiguous. For example, assume the alphabet consists of a and b, the start symbol is S, and we have the following production rules: then we start with S, and can choose a rule to apply to it. If we choose rule 1, we obtain the string aSb. If we then choose rule 1 again, we replace S with aSb and obtain the string aaSbb. If we now choose rule 2, we replace S with ba and obtain the string aababb, and are done. We can write this series of choices more briefly, using symbols: . The language of the grammar is then the infinite set , where is repeated times (and in particular represents the number of times production rule 1 has been applied). Formal definition[edit] The syntax of grammars[edit] In the classic formalization of generative grammars first proposed by Noam Chomsky in the 1950s,[1][2] a grammar G consists of the following components: - A finite set N of nonterminal symbols, that is disjoint with the strings formed from G. - A finite set of terminal symbols that is disjoint from N. - A finite set P of production rules, each rule of the form - where is the Kleene star operator and denotes set union. That is, each production rule maps from one string of symbols to another, where the first string (the "head") contains an arbitrary number of symbols provided at least one of them is a nonterminal. In the case that the second string (the "body") consists solely of the empty string – i.e., that it contains no symbols at all – it may be denoted with a special notation (often , e or ) in order to avoid confusion. - A distinguished symbol that is the start symbol, also called the sentence symbol. A grammar is formally defined as the tuple . Such a formal grammar is often called a rewriting system or a phrase structure grammar in the literature.[3][4] The semantics of grammars[edit] The operation of a grammar can be defined in terms of relations on strings: - Given a grammar , the binary relation (pronounced as "G derives in one step") on strings in is defined by: - the relation (pronounced as G derives in zero or more steps) is defined as the reflexive transitive closure of - a sentential form is a member of that can be derived in a finite number of steps from the start symbol ; that is, a sentential form is a member of . A sentential form that contains no nonterminal symbols (i.e. is a member of ) is called a sentence.[5] - the language of , denoted as , is defined as all those sentences that can be derived in a finite number of steps from the start symbol ; that is, the set . Note that the grammar is effectively the semi-Thue system , rewriting strings in exactly the same way; the only difference is in that we distinguish specific nonterminal symbols which must be rewritten in rewrite rules, and are only interested in rewritings from the designated start symbol to strings without nonterminal symbols. Example[edit] For these examples, formal languages are specified using set-builder notation. Consider the grammar where , , is the start symbol, and consists of the following production rules: This grammar defines the language where denotes a string of n consecutive 's. Thus, the language is the set of strings that consist of 1 or more 's, followed by the same number of 's, followed by the same number of 's. Some examples of the derivation of strings in are: - (Note on notation: reads "String P generates string Q by means of production i", and the generated part is each time indicated in bold type.) The Chomsky hierarchy[edit] When Noam Chomsky first formalized generative grammars in 1956,[1] he classified them into types now known as the Chomsky hierarchy. The difference between these types is that they have increasingly strict production rules and can express fewer formal languages. Two important types are context-free grammars (Type 2) and regular grammars (Type 3). The languages that can be described with such a grammar are called context-free languages and regular languages, respectively. Although much less powerful than unrestricted grammars (Type 0), which can in fact express any language that can be accepted by a Turing machine, these two restricted types of grammars are most often used because parsers for them can be efficiently implemented.[6] For example, all regular languages can be recognized by a finite state machine, and for useful subsets of context-free grammars there are well-known algorithms to generate efficient LL parsers and LR parsers to recognize the corresponding languages those grammars generate. Context-free grammars[edit] A context-free grammar is a grammar in which the left-hand side of each production rule consists of only a single nonterminal symbol. This restriction is non-trivial; not all languages can be generated by context-free grammars. Those that can are called context-free languages. The language defined above is not a context-free language, and this can be strictly proven using the pumping lemma for context-free languages, but for example the language (at least 1 followed by the same number of 's) is context-free, as it can be defined by the grammar with , , the start symbol, and the following production rules: A context-free language can be recognized in time (see Big O notation) by an algorithm such as Earley's algorithm. That is, for every context-free language, a machine can be built that takes a string as input and determines in time whether the string is a member of the language, where is the length of the string.[7] Deterministic context-free languages is a subset of context-free languages that can be recognized in linear time.[8] There exist various algorithms that target either this set of languages or some subset of it. Regular grammars[edit] In regular grammars, the left hand side is again only a single nonterminal symbol, but now the right-hand side is also restricted. The right side may be the empty string, or a single terminal symbol, or a single terminal symbol followed by a nonterminal symbol, but nothing else. (Sometimes a broader definition is used: one can allow longer strings of terminals or single nonterminals without anything else, making languages easier to denote while still defining the same class of languages.) The language defined above is not regular, but the language (at least 1 followed by at least 1 , where the numbers may be different) is, as it can be defined by the grammar with , , the start symbol, and the following production rules: All languages generated by a regular grammar can be recognized in linear time by a finite state machine. Although, in practice, regular grammars are commonly expressed using regular expressions, some forms of regular expression used in practice do not strictly generate the regular languages and do not show linear recognitional performance due to those deviations. Other forms of generative grammars[edit] Many extensions and variations on Chomsky's original hierarchy of formal grammars have been developed, both by linguists and by computer scientists, usually either in order to increase their expressive power or in order to make them easier to analyze or parse. Some forms of grammars developed include: - Tree-adjoining grammars increase the expressiveness of conventional generative grammars by allowing rewrite rules to operate on parse trees instead of just strings.[9] - Affix grammars[10] and attribute grammars[11][12] allow rewrite rules to be augmented with semantic attributes and operations, useful both for increasing grammar expressiveness and for constructing practical language translation tools. Recursive grammars[edit] A recursive grammar is a grammar which contains production rules that are recursive. For example, a grammar for a context-free language is left-recursive if there exists a non-terminal symbol A that can be put through the production rules to produce a string with A as the leftmost symbol.[13] All types of grammars in the Chomsky hierarchy can be recursive. Analytic grammars[edit] Though there is a tremendous body of literature on parsing algorithms, most of these algorithms assume that the language to be parsed is initially described by means of a generative formal grammar, and that the goal is to transform this generative grammar into a working parser. Strictly speaking, a generative grammar does not in any way correspond to the algorithm used to parse a language, and various algorithms have different restrictions on the form of production rules that are considered well-formed. An alternative approach is to formalize the language in terms of an analytic grammar in the first place, which more directly corresponds to the structure and semantics of a parser for the language. Examples of analytic grammar formalisms include the following: - The Language Machine directly implements unrestricted analytic grammars. Substitution rules are used to transform an input to produce outputs and behaviour. The system can also produce the lm-diagram which shows what happens when the rules of an unrestricted analytic grammar are being applied. - Top-down parsing language (TDPL): a highly minimalist analytic grammar formalism developed in the early 1970s to study the behavior of top-down parsers.[14] - Link grammars: a form of analytic grammar designed for linguistics, which derives syntactic structure by examining the positional relationships between pairs of words.[15][16] - Parsing expression grammars (PEGs): a more recent generalization of TDPL designed around the practical expressiveness needs of programming language and compiler writers.[17] See also[edit] References[edit] - ^ a b Chomsky, Noam (Sep 1956). "Three models for the description of language". IRE Transactions on Information Theory 2 (3): 113–124. Archived from the original on 2013-10-18. - ^ Chomsky, Noam (1957). Syntactic Structures. The Hague: Mouton. - ^ Ginsburg, Seymour (1975). Algebraic and automata theoretic properties of formal languages. North-Holland. - ^ Harrison, Michael A. (1978). Introduction to Formal Language Theory. Reading, Mass.: Addison-Wesley Publishing Company. - ^ Sentential Forms, Context-Free Grammars, David Matuszek - ^ Grune, Dick & Jacobs, Ceriel H., Parsing Techniques – A Practical Guide, Ellis Horwood, England, 1990. - ^ Earley, Jay, "An Efficient Context-Free Parsing Algorithm," Communications of the ACM, Vol. - ^ Knuth, D. E. (July 1965). "On the translation of languages from left to right". Information and Control 8 (6): 607–639. Retrieved 29 May 2011. - ^ Joshi, Aravind K., et al., "Tree Adjunct Grammars," Journal of Computer Systems Science, Vol. - ^ Koster , Cornelis H. A., "Affix Grammars," in ALGOL 68 Implementation, North Holland Publishing Company, Amsterdam, p. 95-109, 1971. - ^ Knuth, Donald E., "Semantics of Context-Free Languages," Mathematical Systems Theory, Vol. - ^ Knuth, Donald E., "Semantics of Context-Free Languages (correction)," Mathematical Systems Theory, Vol. - ^ Notes on Formal Language Theory and Parsing, James Power, Department of Computer Science National University of Ireland, Maynooth Maynooth, Co. Kildare, Ireland.JPR02 - ^ Birman, Alexander, The TMG Recognition Schema, Doctoral thesis, Princeton University, Dept. of Electrical Engineering, February 1970. - ^ Sleator, Daniel D. & Temperly, Davy, "Parsing English with a Link Grammar," Technical Report CMU-CS-91-196, Carnegie Mellon University Computer Science, 1991. - ^ Sleator, Daniel D. & Temperly, Davy, "Parsing English with a Link Grammar," Third International Workshop on Parsing Technologies, 1993. (Revised version of above report.) - ^ Ford, Bryan, Packrat Parsing: a Practical Linear-Time Algorithm with Backtracking, Master’s thesis, Massachusetts Institute of Technology, Sept. 2002.