Question

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?

Was it helpful?

Solution

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)
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top