Search code examples
kotlinfunctional-programmingmonadsmonad-transformersarrow-kt

Kotlin elegant way to mutate List<Triple<String, String, String> to Triple<List<String>, List<String>, List<String>>


I'd like, as succinctly (yet clearly) as possible to transform a List<Triple<String, String, String> to a Triple<List<String>, List<String>, List<String>>.

For instance, say the method performing the transformation is called turnOver, I'd expect:

val matches = listOf(
  Triple("a", "1", "foo"),
  Triple("b", "2", "bar"),
  Triple("c", "3", "baz"),
  Triple("d", "4", "qux")
)
val expected = Triple(
  listOf("a", "b", "c", "d"),
  listOf("1", "2", "3", "4"),
  listOf("foo", "bar", "baz", "qux")
)
matches.turnOver() == expected // true

How to write a succinct, clear, and possibly functional turnOver function?

It's ok to use Arrow-Kt, I already got it as project dependency.


Solution

  • fun turnOver(matches: List<Triple<String, String, String>>) = Triple(
       matches.map { it.first },
       matches.map { it.second },
       matches.map { it.third },
    )
    

    would be one obvious solution I reckon.