Passing functions for all applicable types around

前端 未结 4 1514
广开言路
广开言路 2021-01-05 14:02

I followed the advice found here to define a function called square, and then tried to pass it to a function called twice. The functions are defined like this:



        
4条回答
  •  鱼传尺愫
    2021-01-05 15:06

    Here's a session from the Scala REPL.

    Welcome to Scala version 2.8.0.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_20).
    Type in expressions to have them evaluated.
    Type :help for more information.
    
    scala> def square[T : Numeric](n: T) = implicitly[Numeric[T]].times(n, n)
    square: [T](n: T)(implicit evidence$1: Numeric[T])T
    
    scala> def twice2[T](f: T => T)(a: T) = f(f(a))
    twice2: [T](f: (T) => T)(a: T)T
    
    scala> twice2(square)(3)
    :8: error: could not find implicit value for evidence parameter of type
     Numeric[T]
           twice2(square)(3)
                  ^
    
    scala> def twice3[T](a: T, f: T => T) = f(f(a))
    twice3: [T](a: T,f: (T) => T)T
    
    scala> twice3(3, square)
    :8: error: could not find implicit value for evidence parameter of type
     Numeric[T]
           twice3(3, square)
    
    scala> def twice[T](a: T)(f: T => T) = f(f(a))
    twice: [T](a: T)(f: (T) => T)T
    
    scala> twice(3)(square)
    res0: Int = 81
    

    So evidently the type of "twice(3)" needs to be known before the implicit can be resolved. I guess that makes sense, but I'd still be glad if a Scala guru could comment on this one...

提交回复
热议问题