I wrote the following Haskell code using do-nation.
And I'd like to convert it to Scala code
main :: IO ()
main = do
print $ func1 (Right 1) (Right 2)
print $ func1 (Right 10) (Right 3)
func1 :: Either String Int -> Either String Int -> Either String Double
func1 e1 e2 = do
v1 <- e1
v2 <- e2
if v1 < v2
then Right 1.515151 -- No meaning
else Left "some error"
Here is output of Haskell
Right 1.515151
Left "some error"
I wrote Scala code like the following. But I feel weird when I look at result <- if(v1 < v2)... and yield result.
object Main {
def main(args: Array[String]): Unit = {
println(func1(Right(1))(Right(2)))
println(func1(Right(10))(Right(3)))
}
def func1(e1: Either[String, Int])(e2: Either[String, Int]): Either[String, Double] =
for{
v1 <- e1
v2 <- e2
// Weird...
result <- if(v1 < v2)
Right(1.515151)
else
Left("some error")
} yield result
}
Here is output of Scala
Right(1.515151)
Left(some error)
I'd like to write bellow. But Scala doesn't allow me to write.
// Invalid Scala Code
def func1(e1: Either[String, Int])(e2: Either[String, Int]): Either[String, Double] =
for{
v1 <- e1
v2 <- e2
} {
if(v1 < v2)
Right(1.515151)
else
Left("some error")
}
Could you tell me your idea for writing in beautiful way?