How can I use Shapeless to create a function abstracting over arity

前端 未结 2 1283
终归单人心
终归单人心 2021-02-06 08:40

Let\'s consider a specific example. I have lots of functions that take a variable number of arguments, and return a Seq[T]. Say:

def nonNeg(start: I         


        
2条回答
  •  礼貌的吻别
    2021-02-06 09:16

    For 2 and more (in code below to 4) parameters you can use implicit parameters feature, for resolve result type by input parameter type

    sealed trait FuncRes[F] {
      type Param
      type Result
      def func : F => Param => Result
    }
    
    class Func[T, R](fn : T => R) {
      trait FR[F, P] extends FuncRes[F] { type Param = P; type Result = R }
    
      implicit def func2[T1,T2] = new FR[(T1,T2) => T, (T1,T2)] {
        def func = f => p => fn(f.tupled(p))
      }
    
      implicit def func3[T1,T2,T3] = new FR[(T1,T2,T3) => T, (T1,T2,T3)] {
        def func = f => p => fn(f.tupled(p))
      }
    
      implicit def func4[T1,T2,T3,T4] = new FR[(T1,T2,T3,T4) => T, (T1,T2,T3,T4)] {
        def func = f => p => fn(f.tupled(p))
      }
    
      def makeFunc[F](f : F)(implicit ev : FuncRes[F]): ev.Param => ev.Result = 
        ev.func(f)
    }
    

    and after your def javaNonNeg = makeJava(nonNeg) function will look like:

    object asJavaFunc extends Func((_ : Seq[Int]).asJava)  
    import asJavaFunc._
    
    def javaNonNeq = makeFunc(nonNeg _)  
    

    And of course it has some disadvantages, but generally it satisfy your needs.

提交回复
热议问题