Pipe-forward operator |>


#21

I know, but with your solution one should maintain a zoo of extension functions from project to project for different set of libraries. With appropriate import option it should became less messy.


#22

After fiddling with the problem, I finally wrote those:

fun add(x: Int): Int = x + 1
fun mul(x: Int): Int = x * 12

class Pipe<out A>(val v: A) {
    inline infix fun <B> andThen(function: (A) -> B) = Pipe(function(v))
}

infix fun <T, R> T.into(other: (T) -> R) = Pipe(other(this))

fun main(args: Array<String>) {
    5 into ::add andThen ::mul andThen ::println
}

I think it works quite great without adding anything to Kotlin itslef


#23

You do not need the Pipe class for that. You do always create an object for each result, but why?

infix fun <T, R> T.into(func: (T) -> R) = func(this)

should be sufficient. It looks like that:

fun main(args: Array<String>) {
     args[0].toDouble() into ::sqrt into Double::inc into ::println
}

I think, that would make the operator pretty much useless, because it is just one line of code enabling the rail (or pipe or whatever).


#24

It can be done in many ways, below code worked very well with me:

package hello

fun main(args: Array<String>) {
    var a = 3
    val b: Int = 6


    println("Hello World! doubling, then tripling the sume of $a and $b is " +
            "${(sumx(a,b)
                    next ::dbl
                    next ::trpl
                    )}")

    println("Hello World! doubling, then tripling the sume of $a and $b is " +
            "${(sumx(a,b)
                    .let (::dbl)
                    .let (::trpl)
                    )}")
    println("Hello World! doubling, then tripling the sume of $a and $b is " +
            "${(sumx(a,b)
                    .run (::dbl)
                    .run (::trpl)
                    )}")

    println("Hello World! doubling, then tripling the sume of $a and $b is " +
            "${(sumx(a,b)
                    into (::dbl)
                    into (::trpl)
                    )}")
}

fun sumx (x: Int, y: Int) : Int = x + y
fun dbl (x: Int): Int = x * 2
fun trpl (x: Int): Int = x * 3

infix fun <T, R> T.next(map : (T) -> R) : R = map(this)
infix fun <T, R> T.into(func: (T) -> R) = func(this)

The output is same in all cases, as:

Hello World! doubling, then tripling the sume of 3 and 6 is 54
Hello World! doubling, then tripling the sume of 3 and 6 is 54
Hello World! doubling, then tripling the sume of 3 and 6 is 54
Hello World! doubling, then tripling the sume of 3 and 6 is 54


#25

FWIW, a pipe-forward operator would be very much welcome, and it seems within the idiom of the language.

For example, the coroutine documentation makes references to pipelines – it would be useful to be able to pipe coroutines together
|> coroutine1
|> coroutine2
|> coroutine3