Scala: (Int, Int) => Int does not match (Int, Int) => Int

I am trying to use 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 get an error message:

 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 archive all the arguments, then there is 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 an unpublished version?

+4
source share
1 answer

Bit with (g) => (x :Int,y :Int) => . Scala expects your argument to be a tuple (Int, Int), so it will be more like (g) => (tup: (Int, Int)) =>

You can use the pattern matching bit to avoid using _1 and _2 matching over tup. This compiles fine for me:

 def gcd = y[(Int, Int), Int](g => { case (x,y) => if(x == 0) y else g(y % x, x) }) 
+8
source

Source: https://habr.com/ru/post/1392155/


All Articles