在 Scala 中,如何调用一个以二元组作为参数并以 returns 二元组作为结果的函数?
How do you call a function which takes a tuple of two as an argument and returns a tuple of two as a result in Scala?
我是 Scala 的新手。我被分配了编写快速斐波那契算法的任务。在实际调用该函数时,我发现它很困难。该函数采用二元组和 returns 作为结果的二元组。我不知道我的 fibStep 逻辑是否正确,但我会在实际测试该功能后尽快解决。以下是我目前所拥有的:
def fastFib(x: Long ): Long = {
def fibStep(x:(Long, Long)): (Long, Long) = {
//setting temporary variables a and b
def a = x._1
def b = x._2
//applying the fast Fibonacci algorithm
def c = a * (b * 2 - a)
def d = a * a + b * b
if (c+d % 2 == 0) return (c,d)
else return (d, c+d)
}
def tuple = (x-1,x-2)
return fibStep(tuple)
}
我需要将元组 (x-1,x-2) 传递给 fibStep。我该怎么做?谢谢
问题出在 return 语句中。你试图 return 元组,而不是长元组。
修复:
def fastFib(x: Long ): Long = {
...
return fibStep(tuple)._1 // or ._2
}
注意:我不确定你的算法是否正确
你这里有很多问题。
def
用于定义函数
val
应该用来定义变量
return
不应使用。你 'return' 一个结果只是因为它是表达式中的最后一个值。
元组仅使用括号定义:
val myTuple = (1,2)
有了这些信息,您应该能够做出更好的尝试。
我是 Scala 的新手。我被分配了编写快速斐波那契算法的任务。在实际调用该函数时,我发现它很困难。该函数采用二元组和 returns 作为结果的二元组。我不知道我的 fibStep 逻辑是否正确,但我会在实际测试该功能后尽快解决。以下是我目前所拥有的:
def fastFib(x: Long ): Long = {
def fibStep(x:(Long, Long)): (Long, Long) = {
//setting temporary variables a and b
def a = x._1
def b = x._2
//applying the fast Fibonacci algorithm
def c = a * (b * 2 - a)
def d = a * a + b * b
if (c+d % 2 == 0) return (c,d)
else return (d, c+d)
}
def tuple = (x-1,x-2)
return fibStep(tuple)
}
我需要将元组 (x-1,x-2) 传递给 fibStep。我该怎么做?谢谢
问题出在 return 语句中。你试图 return 元组,而不是长元组。
修复:
def fastFib(x: Long ): Long = {
...
return fibStep(tuple)._1 // or ._2
}
注意:我不确定你的算法是否正确
你这里有很多问题。
def
用于定义函数
val
应该用来定义变量
return
不应使用。你 'return' 一个结果只是因为它是表达式中的最后一个值。
元组仅使用括号定义:
val myTuple = (1,2)
有了这些信息,您应该能够做出更好的尝试。