线程`尝试通过理解

时间:2012-08-16 14:57:48

标签: validation scala pattern-matching scala-2.10 for-comprehension

another question触发(虽然后来已被编辑过),但我想尝试将调用链接到Scala 2.10的Try构造是多么容易(参见{{3使用for-comprehensions。

这个想法是拥有一个令牌列表并将它们与一系列模式匹配,然后返回第一个错误或成功匹配的模式。我到达了以下非常笨拙的版本,我想知道这是否可以变得更简单和更好:

import util.Try

trait Token
case class Ident  (s: String) extends Token
case class Keyword(s: String) extends Token
case class Punct  (s: String) extends Token
case object NoToken extends Token
case class FunctionDef(id: Ident)

case class Expect[A](expectation: String)(pattern: PartialFunction[Token, A]) {
  def unapply(tup: (Try[_], Token)) = Some(tup._1.map { _ => 
     pattern.lift(tup._2).getOrElse(throw new Exception(expectation))
  })
}

现在构建对Keyword("void") :: Ident(id) :: Punct("(") :: Punct(")") :: tail

的期望
val hasVoid   = Expect("function def starts with void") { case Keyword("void") => }
val hasIdent  = Expect("expected name of the function") { case id: Ident       => id }
val hasOpen   = Expect("expected opening parenthesis" ) { case Punct("(")      => }
val hasClosed = Expect("expected closing parenthesis" ) { case Punct(")")      => }

构建完整的测试用例:

def test(tokens: List[Token]) = {
  val iter = tokens.iterator
  def next(p: Try[_]) = Some(p -> (if (iter.hasNext) iter.next else NoToken))
  def first() = next(Try())

  val sq = for {
    hasVoid  (vd) <- first()
    hasIdent (id) <- next(vd)
    hasOpen  (op) <- next(id)
    hasClosed(cl) <- next(op)
  } yield cl.flatMap(_ => id).map(FunctionDef(_))

  sq.head
}

以下验证测试方法:

// the following fail with successive errors
test(Nil)
test(Keyword("hallo") :: Nil)
test(Keyword("void" ) :: Nil)
test(Keyword("void" ) :: Ident("name") :: Nil)
test(Keyword("void" ) :: Ident("name") :: Punct("(") :: Nil)
// this completes
test(Keyword("void" ) :: Ident("name") :: Punct("(") :: Punct(")") :: Nil)

现在尤其是flatMap中的其他mapyield似乎很糟糕,以及需要在理解结果上调用head

有什么想法吗? Try非常适合理解吗?不应该EitherTry“固定”以允许这种类型的线程(例如,允许Try作为直接结果类型unapply)?

1 个答案:

答案 0 :(得分:4)

诀窍似乎是内部结构中创建Try个实例,而是让它抛出异常并构造一个外部< / em> Try

首先,让我们摆脱Try[Unit]

case class Expect(expectation: String)(pattern: PartialFunction[Token, Unit]) {
  def unapply(token: Token) = 
    pattern.isDefinedAt(token) || (throw new Exception(expectation))
}

case class Extract[A](expectation: String)(pattern: PartialFunction[Token, A]) {
  def unapply(token: Token) = Some(
    pattern.lift(token).getOrElse(throw new Exception(expectation))
  )
}

然后检查成为:

val hasVoid   = Expect ("function def starts with void") { case Keyword("void") => }
val getIdent  = Extract("expected name of the function") { case id: Ident       => id }
val hasOpen   = Expect ("expected opening parenthesis" ) { case Punct("(")      => }
val hasClosed = Expect ("expected closing parenthesis" ) { case Punct(")")      => }

测试方法:

def test(tokens: List[Token]) = Try {
  val iter = tokens.iterator
  def next() = Some(if (iter.hasNext) iter.next else NoToken)

  (for {
    hasVoid()    <- next()
    getIdent(id) <- next()
    hasOpen()    <- next()
    hasClosed()  <- next()
  } yield FunctionDef(id)).head  // can we get rid of the `head`?
}