Dependent Values

95 views
Skip to first unread message

Joheinz

unread,
Feb 3, 2015, 5:04:36 PM2/3/15
to sca...@googlegroups.com
Hi all,

I have a problem with a solution, but somehow the feeling that I reinvented the wheel.


I have some datastructure with optional values:
case class Test(a: Option[String], b: Option[String])

and some means to acquire this individual values:
type S[A] = Error.type \/ Option[A]

And essentially I want to function, which solves:
assert(createTest("ha".some.right, "ba".some.right) == \/-(Some(Test(Some("ha"),Some("ba")))))
assert(createTest("ha".some.right, none.right) == \/-(Some(Test(Some("ha"),None))))
assert(createTest(none.right, "ba".some.right) == -\/(Error))
assert(createTest(none.right, none.right) == \/-(Some(Test(None,None))))
assert(createTest(Error.left, "ba".some.right) == -\/(Error))

where any acquiring of data is an error, and on the right I get my datastructure,
if b is only set when a is set, when a is set, or when both are none.
If b is set without a it is an error.

I wrote:
def createTest(a: S[String], b: S[String]): S[Test] = {
val x = (a |@| b).tupled
if (x.isLeft) Error.left else {
x.flatMap {
case (Some(x), y) => Test(x.some, y).some.right
case (None, None) => Test(none, none).some.right
case (None, Some(y)) => Error.left
case _ => none.right
}
}
}

which feels clumsy. Is there a better way? I tried with applicatives and for comprehensions, but there was always a case which did not fit. My guess, is that I am mssing something useful.

Thanks for your help,
Markus

Stephen Compall

unread,
Mar 1, 2015, 5:44:55 PM3/1/15
to sca...@googlegroups.com
On Tue, 2015-02-03 at 23:04 +0100, Joheinz wrote:
    if (x.isLeft) Error.left else { 

This line does nothing.


case (None, None)    => Test(none, none).some.right 
case (None, Some(y)) => Error.left 

Some awkwardness is inevitable, because this is an awkward rule.

case _               => none.right 

It's too bad that you didn't get an unreachable code warning for this line.  Even though it's technically reachable because of that stupid null.


-- 
Stephen Compall
"^aCollection allSatisfy: [:each|aCondition]": less is better
signature.asc
Reply all
Reply to author
Forward
0 new messages