Scala pattern matching aggregate multiple matches -
if have case class
case class test(a: option[boolean], b: option[boolean], c: option[boolean], d: option[boolean])
and have find out boolean
result of parameters of class test
amount to. example:
test(none, none, some(true), some(false))
should result in false
and
test(some(true), none, some(true), none)
would result in true
i thinking use pattern matching, have match every possible scenario , that's lot, plus if adding more parameters code grows exponentially.
but like
test(some(true), none, some(true), none) match { case (_, _, _, some(b)) => b case (_, _, some(b), _) => b case (_, some(b), _, _) => b case (some(b), _, _, _) => b }
and aggregate b
's single boolean
result?
for conjunction of defined arguments, consider this,
case class test(a: option[boolean], b: option[boolean], c: option[boolean], d: option[boolean]) { def and() = this.productiterator .collect { case some(b: boolean) => b }.reduce(_&&_) }
a case classes extend trait product
equip instances methods processing arguments.
thus,
test(none, none, some(true), some(false)).and() res: false test(some(true), none, some(true), none).and() res: true
here iterate on values of type any
delivered productiterator
, , collect defined , convertible boolean
; call reduce
deliver conjunction of collected boolean
.
update
a well-defined version,
case class test(a: option[boolean], b: option[boolean], c: option[boolean], d: option[boolean]) { def and() = { val b = this.productiterator.collect { case some(b: boolean) => b } if (b.isempty) false else b.reduce(_&&_) } }
Comments
Post a Comment