Skip to content

Instantly share code, notes, and snippets.

@lizixroy
Last active July 28, 2016 03:03
Show Gist options
  • Save lizixroy/517c386c0292af093c564aae65c9f984 to your computer and use it in GitHub Desktop.
Save lizixroy/517c386c0292af093c564aae65c9f984 to your computer and use it in GitHub Desktop.
Language
class Language {
private let separator = ", "
private var productions = [String: [String]]()
init(setUpProductionRules: Bool) {
if setUpProductionRules {
self.setUpProductionRules()
}
}
func recognize(arr1 arr1: [ParseTreeNode], arr2: [ParseTreeNode]) -> [ParseTreeNode]? {
var nodes = [ParseTreeNode]()
for node1 in arr1 {
for node2 in arr2 {
let key = [node1.nonTerminal, node2.nonTerminal].joinWithSeparator(separator)
if let nonTerminals = productions[key] {
for nonTerminal in nonTerminals {
let node = ParseTreeNode(nonTerminal: nonTerminal, leftNode: node1, rightNode: node2)
nodes.append(node)
}
}
}
}
return (nodes.count > 0) ? nodes : nil
}
private func setUpProductionRules() {
addGrammar(leftHandSide: "VP", rightHandSide: ["Verb", "NP"])
addGrammar(leftHandSide: "NP", rightHandSide: ["Det", "Noun"])
addLexicon(leftHandSide: "Verb", rightHandSide: ["book"])
addLexicon(leftHandSide: "Det", rightHandSide: ["that"])
addLexicon(leftHandSide: "Noun", rightHandSide: ["flight"])
}
func printGrammarAndLexicon() {
var dict = [String: [String]]()
var keys = productions.keys
for key in keys {
let value = productions[key]!
for nonTerminal in value {
if dict[nonTerminal] == nil {
dict[nonTerminal] = [key]
} else {
dict[nonTerminal]?.append(key)
}
}
}
keys = dict.keys
for key in keys {
let array = dict[key]!
for str in array {
print("\(key) -> \(str)")
}
}
}
func addGrammar(leftHandSide leftHandSide: String, rightHandSide: [String]) {
let key = rightHandSide.joinWithSeparator(separator)
if productions[key] != nil {
productions[key]?.append(leftHandSide)
} else {
productions[key] = [leftHandSide]
}
}
func addLexicon(leftHandSide leftHandSide: String, rightHandSide: [String]) {
for word in rightHandSide {
if productions[word] != nil {
productions[word]?.append(leftHandSide)
} else {
productions[word] = [leftHandSide]
}
}
}
func recognize(rightHandSide: [String]) -> [String]? {
let key = rightHandSide.joinWithSeparator(separator)
return productions[key]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment