sorting - scala parameterised merge sort - confusing error message -
i getting compilation error when calling (lt: (t,t) => boolean) function
error code "type mismatch; found : x.type (with underlying type t) required: t"
, x parameter in lt(x,y) underlined.
object sort { def msort[t](xs: list[t])(lt: (t, t) => boolean): list[t] = { def merge[t](xs: list[t], ys: list[t]): list[t] = (xs, ys) match { case (nil, ys) => ys case (xs, nil) => xs case (x :: xs1, y :: ys1) => { if (lt(x, y)) x :: merge(xs1, ys) else y :: merge(xs, ys1) } } val n = xs.length / 2 if (n == 0) xs else { val (left, right) = xs splitat n merge(msort(left)(lt), msort(right)(lt)) } } }
msort
, merge
have different type parameters. remove t
type parameter merge
:
def merge(xs: list[t], ys: list[t]): list[t] = (xs, ys) match {
the [t]
declares new parameter unrelated first. same error if declare as:
def merge[u](xs: list[u], ys: list[u]): list[u] = (xs, ys) match {
lt
has type (u, u) => boolean
, , you're calling x
, y
have type t
, don't match.
Comments
Post a Comment