Scala: map with two or more Options -
basically i'm looking scala-like way following:
def sum(value1: option[int], value2: option[int]): option[int] = if(value1.isdefined && value2.isdefined) some(value1.get + value2.get) else if(value1.isdefined && value2.isempty) value1 else if(value1.isempty && value2.isdefined) value2 else none
this gives correct output:
sum(some(5), some(3)) // result = some(8) sum(some(5), none) // result = some(5) sum(none, some(3)) // result = some(3) sum(none, none) // result = none
yet sum more 2 options i'd have use way many if
s or use sort of loop.
edit-1:
while writing question came sort of answer:
def sum2(value1: option[int], value2: option[int]): option[int] = value1.tolist ::: value2.tolist reduceleftoption { _ + _ }
this 1 looks idiomatic inexperienced eye. work more 2 values. yet possible same without converting lists?
edit-2:
i ended solution (thanks ziggystar):
def sum(values: option[int]*): option[int] = values.flatten reduceleftoption { _ + _ }
edit-3:
another alternative landei:
def sum(values: option[int]*): option[int] = values collect { case some(n) => n } reduceleftoption { _ + _ }
how about:
scala> def sum(values: option[int]*): option[int] = values.flatten match { | case nil => none | case l => some(l.sum) | } sum: (values: option[int]*)option[int] scala> sum(some(1), none) res0: option[int] = some(1) scala> sum(some(1), some(4)) res1: option[int] = some(5) scala> sum(some(1), some(4), some(-5)) res3: option[int] = some(0) scala> sum(none, none) res4: option[int] = none
edit
maybe sane return 0 if arguments none. in case function reduce values.flatten.sum
.
Comments
Post a Comment