Hi, Another question. I have two lists, List<A&...
# arrow
s
Hi, Another question. I have two lists, List<A>, and List<B>, and I want to pass them through Ior to perform actions based on if they are empty or not. Only sensible logic I’ve been able to get to so far, is,
Ior.fromNullables(Nel.fromList(list1).getOrElse { null }, Nel.fromList(list2),getOrElse { null})
This is obviously not good, as
Nel<A>?
effectively means
List<A>
, so i can just
list1.isEmpty() && list2.isEmpty
to cover
Ior
cases. However, what I want is
Nel
after checking the states. Is there something better that can be done here ? Pattern matching on
Option<Nel<A>> to Option<Nel<B>>
also doesn’t work. I can’t say for example
when exp is Pair<Some, None>
s
So you want
Ior<Nel<A>, Nel<B>>
? What do you expect if both are empty?
s
I would've hoped it’ll get covered by
Ior<Nel<A>, Nel<B>>?
Then I can just check if Ior is null, then I perform operation that doesn't need any of these lists.
I can Ofcourse make an Ior for example
Ior.fromlists(..)
, but I thought I can ask here first.
s
Right, I would probably go for the first option then. This pattern can be cleaned up if you need it regularly in your downstream project. You can use
orNull()
instead of
getOrElse { null }
though
👍 1
s
By cleaning up the pattern, you mean, me adding some wrappers in my project to achieve it, or introducing an api in the arrow library ?
Also, thanks a lot for the answers. Always appreciate it.
m
@Satyam Agarwal i think you are looking for
Option<A>.align(other: Option<B>, fn: (Ior<A, B>) -> C): Option<C>
?
Copy code
val first: Option<NonEmptyList<Int>> = Nel.fromList(listOf(5))
val second: Option<NonEmptyList<String>> = Nel.fromList(listOf("one"))

val result: Option<...> = first.align(second) { ior: Ior<Nel<Int>, Nel<String>> ->
    // ...
    
}
💯 1
align
will give you a
Some<Ior<A, B>>
if either
Option<A>
or
Option<B>
is some. it will otherwise yield
None
If I understand the question correctly, you’d want to operate on the ior iff one / both of them is defined. In this case you can specify the lambda block after the call to align to immediately to operate on the resulting ior (like the example above) or do a map/flatMap on the option or do it within an
option { }
context if you’d wish to have a more complex operation, i.e.:
Copy code
option { 
    val ior: Ior<NonEmptyList<A>, NonEmptyList<B>> = maybeNelA.align(maybeNelB).bind()
    // do more things here if ior is defined
}
🔝 1
s
Amazing !!!! Thank you so much !