Created
March 11, 2019 03:47
-
-
Save kmizu/80f16a113221a729f645c32a5c3747fe to your computer and use it in GitHub Desktop.
Parses parens
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sealed abstract class Nest | |
case class NLeaf(code: Char) extends Nest | |
case class NList(elements: List[Nest]) extends Nest | |
def group(tokens: List[Char]): List[Nest] = { | |
def process(nest: List[Nest], acc: List[Nest], remain: List[Char]): (List[Nest], List[Nest], List[Char]) = { | |
remain match { | |
case Nil => | |
(nest, Nil, Nil) | |
case ('(')::rest => | |
val (n, a, r) = process(Nil, nest, rest) | |
process(n ::: acc, a, r) | |
case (')')::rest => | |
process(NList(nest) :: Nil ::: acc, Nil, rest) | |
case t::rest => | |
process(NLeaf(t) :: nest, acc, rest) | |
} | |
} | |
def reverse(nest: List[Nest]): List[Nest] = { | |
nest.reverse.map { | |
case n@NLeaf(_) => n | |
case n@NList(es) => NList(reverse(n.elements)) | |
} | |
} | |
val (nest, _, _) = process(Nil, Nil, tokens) | |
reverse(nest) | |
} | |
println(group(List('a', 'b', '(', 'c', 'd', ')'))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment