Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8402655
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T22:07:38+00:00 2026-06-09T22:07:38+00:00

Triggered by another question (which has been subsequently edited away though), I wanted to

  • 0

Triggered by another question (which has been subsequently edited away though), I wanted to try out how easy it would be to chain calls to Scala 2.10’s Try construct (cf. this presentation), using for-comprehensions.

The idea is to have a list of tokens and match them against a sequence of patterns, then return the first error or the successfully matched pattern. I arrived at the following pretty awkward version, and I wonder if this can be made simpler and nicer:

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))
  })
}

Now construct the expectations for 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(")")      => }

Construct a full test case:

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 verifies the test mehod:

// 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)

Now especially the additional flatMap and map in yield seems horrible, as well as the need to call head on the result of the for comprehension.

Any ideas? Is Try very badly suited for for comprehensions? Shouldn’t either Either or Try be “fixed” to allow for this type of threading (e.g. allow Try as a direct result type of unapply)?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T22:07:39+00:00Added an answer on June 9, 2026 at 10:07 pm

    The trick seems to be to not create Try instances in the inner structure, but instead let that throw exceptions and construct one outer Try.

    First, let’s get rid of the Try[Unit]‘s:

    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))
      )
    }
    

    Then the checks become:

    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(")")      => }
    

    And the test method:

    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`?
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Ok guys I know this question has been asked before but I am very
I'm working on a trigger which needs to re-insert its data on another table.
I'm confused as to how to accomplish this. I have a page which, has
This is specifically related to the accepted answer of another question I asked .
I have a simlair problem as in this question: AttributeError: 'module' object has no
I have another question. XMLhttpRequests haunt me. Everything is now in the database but
This is a more specific question to follow up on [another question that I
My question is about test files by which I mean non-code files on which
For another question, I'm running into a misconception that seems to arise here at
I hope this is a simple enough question for any SQL people out there...

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.