1

I am writing a parameterized merge sort functionality and passing the less checker as a function. However, the compiler is throwing following error.

type mismatch;
 found   : y.type (with underlying type T)
 required: T

Here is my full code

def mergeSort[T] (list:List[T], pred:(T,T) =>Boolean):List[T]={
  def merge[T](left:List[T], right:List[T], acc:List[T]):List[T] = (left,right) match{
    case (Nil,_) => acc ++ right
    case (_,Nil) => acc ++ left
    case (x::xs, y::ys) => if(pred(y,x)) merge(left,ys,acc :+ y) else merge(xs,right,acc :+ x)
  }
  val m = list.length/2
  if (m == 0) list
  else {
   val (l,r) = list splitAt m
   merge(mergeSort(l,pred), mergeSort(r,pred), List())
  }
}

The problem is at line

if(pred(y,x))

Everything seems logically correct, can't figure out why this is happening? help appreciated.

1
  • just replace merge[T]( with merge(. Commented Dec 19, 2013 at 11:57

1 Answer 1

2

This happens because in your inner function merge you define a type T, it's like you're redefining the one you created in mergeSort. Just change def merge[T] to def merge and keep using T to parameterized your lists left, right, etc. That way you are telling the compiler "This is the same T I defined above in mergeSort".

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.