Book contents
- Frontmatter
- Contents
- Preface
- Introduction
- Part One Iterative Algorithms and Loop Invariants
- Part Two Recursion
- 8 Abstractions, Techniques, and Theory
- 9 Some Simple Examples of Recursive Algorithms
- 10 Recursion on Trees
- 11 Recursive Images.
- 12 Parsing with Context-Free Grammars
- Part Three Optimization Problems
- Part Four Appendix
- Part five Exercise Solutions
- Index
12 - Parsing with Context-Free Grammars
Published online by Cambridge University Press: 05 June 2012
- Frontmatter
- Contents
- Preface
- Introduction
- Part One Iterative Algorithms and Loop Invariants
- Part Two Recursion
- 8 Abstractions, Techniques, and Theory
- 9 Some Simple Examples of Recursive Algorithms
- 10 Recursion on Trees
- 11 Recursive Images.
- 12 Parsing with Context-Free Grammars
- Part Three Optimization Problems
- Part Four Appendix
- Part five Exercise Solutions
- Index
Summary
An important computer science problem is parsing a string according a given context-free grammar. A context-free grammar is a means of describing which strings of characters are contained within a particular language. It consists of a set of rules and a start nonterminal symbol. Each rule specifies one way of replacing a nonterminal symbol in the current string with a string of terminal and nonterminal symbols. When the resulting string consists only of terminal symbols, we stop. We say that any such resulting string has been generated by the grammar.
Context-free grammars are used to understand both the syntax and the semantics of many very useful languages, such as mathematical expressions, Java, and English. The syntax of a language indicates which strings of tokens are valid sentences in that language. The semantics of a language involves the meaning associated with strings. In order for a compiler or natural-language recognizers to determine what a string means, it must parse the string. This involves deriving the string from the grammar and, in doing so, determining which parts of the string are noun phrases, verb phrases, expressions, and terms.
Some context-free grammars have a property called look ahead one. Strings from such grammars can be parsed in linear time by what I consider to be one of the most amazing and magical recursive algorithms. This algorithm is presented in this chapter. It demonstrates very clearly the importance of working within the friends level of abstraction instead of tracing out the stack frames: Carefully write the specifications for each program, believe by magic that the programs work, write the programs calling themselves as if they already work, and make sure that as you recurse, the instance being input gets smaller.
- Type
- Chapter
- Information
- How to Think About Algorithms , pp. 159 - 168Publisher: Cambridge University PressPrint publication year: 2008