我想定义一个适用* 2于其参数的函数,该函数适用于有意义的所有类型.我尝试使用结构类型:
import scala.language.reflectiveCalls
def double[T](x: Any{def * (arg0: Int): T}) = x * 2
Run Code Online (Sandbox Code Playgroud)
它适用于字符串:
scala> double("a")
res85: String = aa
Run Code Online (Sandbox Code Playgroud)
但不是数字:
scala> double(4)
java.lang.NoSuchMethodException: java.lang.Integer.$times(int)
at java.lang.Class.getMethod(Class.java:1778)
at .reflMethod$Method1(<console>:18)
at .double(<console>:18)
... 32 elided
Run Code Online (Sandbox Code Playgroud)
编辑:通过"做我想要的"我的意思是为现有的类型工作,例如数字和字符串,而不仅仅是我自己定义的类.
breakproc中的三个循环一直跳到puts 8?这很反直觉.puts 6?3.times do
puts "outer loop"
break_proc = proc { break }
puts 1
loop do
puts 2
loop do
puts 3
loop do
puts 4
break_proc.call
puts 5
end
puts 6
end
puts 7
end
puts 8
end
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)outer loop 1 2 3 4 8 outer loop 1 2 3 4 8 outer loop 1 2 3 4 8
当我这样定义时fib(1):
def fib(n: Int) = {
lazy val fibs: Stream[BigInt] = 0 #:: 1 #:: fibs.zip(fibs.tail).map{n => n._1 + n._2}
fibs.drop(n).head
}
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
scala> fib(1000000)
java.lang.OutOfMemoryError: Java heap space
Run Code Online (Sandbox Code Playgroud)
另一方面,这很好(2):
def fib = {
lazy val fibs: Stream[BigInt] = 0 #:: 1 #:: fibs.zip(fibs.tail).map{n => n._1 + n._2}
fibs
}
scala> fib.drop(1000000).head
res17: BigInt = 195328212...
Run Code Online (Sandbox Code Playgroud)
此外,如果我按以下方式更改流定义,我可以drop(n).head在函数内调用,也不会得到任何错误(3):
def fib(n: Int) = {
lazy val fibs: (BigInt, BigInt) => Stream[BigInt] = (a, b) => a #:: fibs(b, …Run Code Online (Sandbox Code Playgroud)