斯卡拉解析器组合器:处理重复的类型
问题描述:
我是新来scala语言和它的解析器组合器。我工作的一个任务,并得到了被困在一个要求: 我的要求是得到重复的如Type
:我创建解析器逻辑运算符和字(这意味着字符串)斯卡拉解析器组合器:处理重复的类型
def logicalOperator:Parser[Operator] = "(&&|\\|\\|)".r ^^ {case op => Operator(op)}
def word: Parser[word] = """[a-z\\\s]+""".r ^^ { case x => word(x) }
现在我的输入可能包含由多个操作员分隔的单个单词或重复单词。 对于离:
input1=> once&&upon||time||forest.
input2=> therewasatime // this is also a valid input , it does not have any operators
我将处理字作为每them.In壳体之间的运营商没有操作者存在(即输入一个字,我将处理对单个单词)。
&& operator and || operator would decide the operation. (we can consider it to be similar to && and || operator in case of boolean values , to understand clearly)
我在想一个案例类句子,它将代表一个单词以及多个单词。而在多字的情况下,将含有operator.In情况下单的话,运营商和第二个字是空
case class Sentence(word1:Word, op:Operator, word2:Word).
因此,这将是一个树形结构的叶节点只包含Word和休息节点将包含运营商。
但我不知道如何写句子解析器。 我尝试使用:
def sentence = repsep(word,logicalOperator)^^{// creating sentence object here}.
但我不能从repsep()
操作提取操作。
对此案件的任何建议?
感谢
答
与repsep
的问题是,是抛弃它的第二个参数的结果,你将无法识别使用了哪个运营商。 另一件事是:如果Sentence
只能包含词,而不是其他句子,您希望once&&upon||time||forest
如何表示。在下文中,我假定你的意思是这样的:
trait Node
case class Operator(s: String)
case class Word(s: String) extends Node
case class Sentence(a: Node, op: Operator, b: Node) extends Node
然后,你可以写sentence
这样的:
def sentence: Parser[Node] = word ~ opt(logicalOperator ~ sentence) ^^ {
case w ~ Some(op ~ sentence) ⇒ Sentence(w, op, sentence)
case w ~ None ⇒ w
}
使用这种方法,once&&upon||time||forest
被解析为
Sentence(
Word(once),
Operator(&&),
Sentence(
Word(upon),
Operator(||),
Sentence(
Word(time),
Operator(||),
Word(forest)
)
)
)