Scala: (Int, Int) => Int doesn't match (Int, Int) => Int

4k views Asked by At

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?

1

There are 1 answers

5
Dylan On BEST ANSWER

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:

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