Idiomatic way to create n-ary cartesian product (combinations of several sets of parameters)

后端 未结 5 1140
执笔经年
执笔经年 2020-12-20 18:56

To create all possible combinations of two sets of parameters and perform an action on them, you can do:

setOf(foo, bar, baz).forEach { a ->
    setOf(0,          


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-20 19:10

    I would recommend using Arrow-kt's Applicative on List. See the example:

    val ints = listOf(1, 2, 3, 4)
    val strings = listOf("a", "b", "c")
    val booleans = listOf(true, false)
    
    val combined = ListK.applicative()
        .tupled(ints.k(), strings.k(), booleans.k())
        .fix()
    
    // or use the shortcut `arrow.instances.list.applicative.tupled`
    // val combined = tupled(ints, strings, booleans)
    
    combined.forEach { (a, b, c) -> println("a=$a, b=$b, c=$c") }
    

    Which produces the Cartesian product

    a=1, b=a, c=true

    a=1, b=b, c=true

    a=1, b=c, c=true

    a=2, b=a, c=true

    a=2, b=b, c=true

    a=2, b=c, c=true

    a=3, b=a, c=true

    a=3, b=b, c=true

    a=3, b=c, c=true

    a=4, b=a, c=true

    a=4, b=b, c=true

    a=4, b=c, c=true

    a=1, b=a, c=false

    a=1, b=b, c=false

    a=1, b=c, c=false

    a=2, b=a, c=false

    a=2, b=b, c=false

    a=2, b=c, c=false

    a=3, b=a, c=false

    a=3, b=b, c=false

    a=3, b=c, c=false

    a=4, b=a, c=false

    a=4, b=b, c=false

    a=4, b=c, c=false

提交回复
热议问题