Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin arrow-kt Flatten nested Either

I'm programming using the functional library arrow-kt (formerly known as kategory). I'm using Either monad to aggregate errors or success information of an api call. I got myself into a state (which shouldn't happen in the first place) in which I have a nestet Either monads. I'm trying to flatten the structure to get the inner monad. The documentation is very limited and I couldn't find a way to do It.

Here's an example of a nested Either monad that I would like to flatten:

Either.right(Either.right(Either.left("error")))
like image 715
MaxG Avatar asked Feb 12 '18 18:02

MaxG


1 Answers

You may flatten such a structure with flatten:

import arrow.core.*
import arrow.typeclasses.*

val result = Either.right(Either.right(Either.left("error")))
Either.monad<String>().flatten(result)
// keep flattening until you are happy with the result
// Right(b=Left(a=error))

Or just flatMap:

import arrow.core.*
import arrow.typeclasses.*

val result = Either.right(Either.right(Either.left("error")))
result.flatMap { it.flatMap { it } }
// Left(a=error)

The fact that you ended up with such nested structure probably means that you are not using the right datatype or wrong abstraction at some point in your program as that is kind of a useless value.

If you wish to preserve the left values as indicated in your comment I think a more suitable datatype would be Validated which allows for error accumulation as demonstrated here http://arrow-kt.io/docs/datatypes/validated/

Alternatively Either#fold can help you contemplate both cases and coalesce then into whatever value you wish.

I'm assuming you already run into these where most of this stuff is explained but just in case some useful links that will help you model this with Arrow

  • Docs: http://arrow-kt.io/docs/datatypes/either/
  • Video: https://www.youtube.com/watch?v=q6HpChSq-xc
  • FP Error handling with Arrow: http://arrow-kt.io/docs/patterns/error_handling/

Additionally feel free to swing by our chat channels if you need a more interactive experience with the maintainers and other contributors than SO where we frequently help people of all levels learning FP and Arrow.

  • Gitter: https://gitter.im/arrow-kt/Lobby
  • Slack: https://kotlinlang.slack.com/messages/C5UPMM0A0

Cheers!

like image 166
Raúl Raja Martínez Avatar answered Oct 04 '22 22:10

Raúl Raja Martínez