functional programming - Collapse similar case statements in Scala -


is there elegant way following example using 1 case statement?

foobar match {     case node(leaf(key, value), parent, qux) => {         // parent & qux     }     case node(parent, leaf(key, value), qux) => {         // parent & qux (code same in previous case)     }     // other cases } 

for understanding of going on here: foobar node of binary tree, , match cases when 1 of node's ancestors leaf node. these classes used:

abstract class tree case class node(left: tree, right: tree, critbit: int) extends tree case class leaf(key: string, value:string) extends tree 

you can use custom extractor abstract matching part away logic part:

object leafed {   def unapply(tree: tree) = tree match {     case node(leaf(_, _), parent, qux) => some((parent, qux))     case node(parent, leaf(_, _), qux) => some((parent, qux))     case _ => none   } } 

and can define methods this:

def dosomething(tree: tree): int = tree match {   case leafed(parent, qux) => qux   case _ => -100 } 

which can use this:

scala> val leaf = leaf("foo", "bar") leaf: leaf = leaf(foo,bar)  scala> dosomething(leaf) res7: int = -100  scala> dosomething(node(leaf, node(leaf, leaf, 5), 10)) res8: int = 10  scala> dosomething(node(node(leaf, leaf, 5), leaf, 10)) res9: int = 10 

otherwise you're out of luck—as marth notes above, pattern alternatives aren't going here.


Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

php - Find a regex to take part of Email -