Vavr: Is there any way to chain operations with both Try<Option<?>> monads together?

Created on 15 Jan 2017  路  5Comments  路  Source: vavr-io/vavr

Hi,

Is there any way to chain operations with both Try> monads together?

Below is the example I tried.

Try<Option<String>> str1 = Try.of(()->Option.of("Noor1"));
Try<Option<String>> str2 = Try.of(()->Option.of("Noor2"));

Try<Option<Try<Option<Tuple2<String,String>>>>> result =  str1.map(optStr1 -> optStr1.map( s1 -> str2.map(optStr2 -> optStr2.map(s2 -> Tuple.of(s1,s2)))));

Try<Option<Tuple2<String,String>>> result2 = Match(result).of(
                Case(Failure($()), ex -> Try.failure(ex)),
                Case(Success(None()), none -> Try.of(()->Option.none())),
                Case(Success(Some(Failure($()))), ex -> Try.of (()-> ex.get().get())),
                Case(Success(Some(Success(None()))),none -> Try.of(()->Option.none())),
                Case(Success(Some(Success(Some($())))), value -> Try.of (()-> Option.of(value.get().get().get())))
        );

System.out.println( result2 );

This is quite verbose. Any luck if I can use Monad Transformers?

question

All 5 comments

@noorulhaq Thank you for your question.

The following is equivalent to your solution:

Try<Option<String>> str1 = Try.of(()-> Option.of("Noor1"));
Try<Option<String>> str2 = Try.of(()-> Option.of("Noor2"));
Try<Option<Tuple2<String, String>>> result = str1.flatMap(o1 -> str2.map(o2 -> o1.flatMap(s1 -> o2.map(s2 -> Tuple.of(s1, s2)))));

In most cases flatMap can be used to solve problems that involve combination of wrapped/monadic values.

Does this help?

Damn it! I tried with flatMap but in wrong order. Thumbs up for your help and trillion thumbs down for myself.

@noorulhaq please don't blame youself - the solution wasn't obvious.

Thanks for the buck up. I am writting an article on funtional domain modeling in Java8 using your library. Once, I am finished with that I will share with you the article. We can then discuss some more functional possibilities that are easy to define.

@noorulhaq that sounds great! please don't hesitate to contact me if you have any questions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

yarulan picture yarulan  路  5Comments

manu-m picture manu-m  路  6Comments

rumatoest picture rumatoest  路  5Comments

enelson picture enelson  路  5Comments

maystrovyy picture maystrovyy  路  3Comments