[英]Problem with Scala Function and Call-by-Name
I am trying to loop a the second parameter (exp) in this function that uses call by name parameters.我正在尝试在此 function 中循环使用按名称调用参数的第二个参数(exp)。 The first 3 parameters are the index, boolean to stop loop, and increment function.前 3 个参数是索引,boolean 停止循环,递增 function。 I am getting an output with 10 '()'s when I am trying to loop "hello world" 10 times as seen in the test code.当我尝试循环“hello world”10 次时,我得到了一个 output,如测试代码中所示。 May I get some help with what is wrong here?我可以就这里的问题寻求帮助吗? Thanks谢谢
def forLoop(ival: => Int, f: (Int) => Boolean, g: (Int)=>Int)(exp: => Unit): Unit = {
if(f(ival)==false)
return
else {
println(exp)
forLoop(g(ival),f,g)(exp)
}
}
def f(x: Int): Boolean = { x<10 }
def g(y: Int): Int = { y+1 }
val exp: Unit = "Hello World"
forLoop(0,f,g)("Hello World")
The value "Hello World"
is of type String
however you are assigning it to Unit
值"Hello World"
是String
类型,但是您将其分配给Unit
val exp: Unit = "Hello World"
which compiler expands to哪个编译器扩展为
val exp: Unit = {
"Hello World";
()
}
Note how ()
becomes the value of exp
.注意()
如何变成exp
的值。 Try changing the definition of exp
to尝试将exp
的定义更改为
val exp: String = "Hello World"
and second parameter list to和第二个参数列表
(exp: => String)
If you compile with compiler flag -Wvalue-discard
, for example,例如,如果您使用编译器标志-Wvalue-discard
进行编译,
scala -Wvalue-discard -e 'val exp: Unit = "Hello World"'
you will get a warning你会收到警告
warning: discarded non-Unit value
val exp: Unit = "Hello World"
^
I think this meets your requirements.我认为这符合您的要求。
def forLoop(ival: => Int, f: =>Int => Boolean, g: =>Int=>Int
)(exp: => Unit): Unit =
if (f(ival)) {
exp
forLoop(g(ival),f,g)(exp)
}
def f(x: Int): Boolean = x<10
def g(y: Int): Int = y+1
def exp: Unit = println("Hello World")
forLoop(0,f,g)(exp)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.