How to compose to methods, without duplicate input arguments

后端 未结 2 1137
遥遥无期
遥遥无期 2021-01-05 10:08

Suppose I have two methods

scala> def a(a: Int, b: Int, c: Int) : Int = …
a: (a: Int, b: Int, c: Int)Int

scala> def b(i: Int) : Int = …
b: (i: Int)Int         


        
相关标签:
2条回答
  • 2021-01-05 10:34

    You could convert method a to function and then use method andThen like this:

    def a(a: Int, b: Int, c: Int) : Int = a + b + c
    def b(i: Int) : Int = i * 2
    
    val c = (a _).tupled andThen b
    
    c(1, 1, 1)
    // 6
    

    Note that I have to convert function (Int, Int, Int) => Int to tupled version - ((Int, Int, Int)) => Int - here to use andThen. So result function c accepts Tuple3 as argument.

    You could convert c to untupled version ((Int, Int, Int) => Int) using Function.untupled:

    val untupledC = Function.untupled(c)
    
    untupledC(1, 1, 1)
    // 6
    

    shapeless

    There is no untupled method for function arity > 5.

    You could also use shapeless toProduct/fromProduct methods for any arity like this:

    import shapeless.ops.function._
    import shapeless.ops.function._
    
    val c = (a _).toProduct.andThen(b).fromProduct
    
    0 讨论(0)
  • 2021-01-05 10:53

    Scalaz defines Functor instances for higher-arity functions, so you can just write

    (a _).map(b)
    
    0 讨论(0)
提交回复
热议问题