Scala:(Int,Int)=> Int 不匹配 (Int, Int) => INT
我正在尝试使用 y-combinator 在 scala 中定义 gcd:
object Main {
def y[A,B]( f : (A => B) => A => B ) : A => B = f(y(f))
def gcd = y[(Int,Int),Int]( (g) => (x,y) => if (x == 0) y else g(y % x, x) )
}
但我收到一个错误:
Main.scala:3: error: type mismatch;
found : (Int, Int) => Int
required: (Int, Int) => Int
def gcd = y[(Int,Int),Int]( (g) => (x :Int,y :Int) => if (x == 0) y else g(y % x, x) )
^
如果我柯里化所有参数,那么就没有问题:
def gcd = y[Int,Int => Int]( g => x => y => if (x == 0) y else g(y % x)(x) )
我在未柯里化版本中做错了什么?
I'm trying to use the y-combinator to define gcd in scala:
object Main {
def y[A,B]( f : (A => B) => A => B ) : A => B = f(y(f))
def gcd = y[(Int,Int),Int]( (g) => (x,y) => if (x == 0) y else g(y % x, x) )
}
But I'm getting an error:
Main.scala:3: error: type mismatch;
found : (Int, Int) => Int
required: (Int, Int) => Int
def gcd = y[(Int,Int),Int]( (g) => (x :Int,y :Int) => if (x == 0) y else g(y % x, x) )
^
If I curry all the arguments, then there's no problem:
def gcd = y[Int,Int => Int]( g => x => y => if (x == 0) y else g(y % x)(x) )
What am I doing wrong in the uncurried version?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
带有
(g) => 的位(x:Int,y:Int)=>
。 Scala 期望您的参数是 (Int,Int) 的元组,因此它更像(g) =>; (tup: (Int, Int)) =>
您可以使用一些模式匹配来避免在 tup 上使用
_1
和_2
匹配。这对我来说编译得很好:The bit with
(g) => (x :Int,y :Int) =>
. Scala expects your argument to be a tuple of (Int,Int), so it would be more like(g) => (tup: (Int, Int)) =>
You can use a bit of pattern matching to avoid having to use
_1
and_2
matching on tup. This compiles just fine for me: