Skip to content

Instantly share code, notes, and snippets.

@matklad
Last active August 23, 2016 20:45
Show Gist options
  • Save matklad/e90c063c0b2b63cf6e41f5211d88907f to your computer and use it in GitHub Desktop.
Save matklad/e90c063c0b2b63cf6e41f5211d88907f to your computer and use it in GitHub Desktop.
def parseMany(parse: (String) => Option[(SExpression, String)], input: String): (Seq[SExpression], String) = {
parse(input)
.map { case (x, r1) =>
val (xs, r2) = parseMany(parse, r1)
(x +: xs, r2)
}
.getOrElse((Seq(), input))
}
def parseMany(parse: (String) => Option[(SExpression, String)], input: String): (Seq[SExpression], String) =
iterate (Seq[SExpression](), input) { case (xs, r1) =>
parse(r1).map { case (x, r2) => (x +: xs, r2) }
}
@tailrec
def iterate[T](init: T)(iter: (T) => Option[T]): T = {
iter(init) match {
case None => init
case Some(i) => iterate(i)(iter)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment