i'm new scala may forgive me basic newbie question. have following code snippet.
type pred[a, b] = (a, b) => int; def abs[a, b](p: (a, b) => int): (a, b) => int = (a, b) => if (p(a, b) < 0) -(p(a, b)) else (p(a, b)); def multiply(a: int, b: int): int = * b; def subtract(a: int, b: int): int = - b; val absmultiply = abs(multiply); val abssubstract = abs(subtract); println("abs(10 * 10) = " + absmultiply.apply(10, 10)); println("abs(10 - 100) = " + abssubstract.apply(10, 100));
so i've understand correctly should possible replace (a,b) => int pred[a, b].
def abs[a, b](p: pred[a, b]): pred[a, b] = (a, b) => if (p(a, b) < 0) -(p(a, b)) else (p(a, b));
but compiler exception
type mismatch; found : (int, int) => int required: (a, b) => int type mismatch; found : (int, int) => int required: (a, b) => int
have misunderstood here wrong?
thank help.
cyrill
it works if declare , b contravariant types:
type pred[-a, -b] = (a, b) => int
this necessary because multiply
, subtract
functions considered subtypes of pred[a, b], arguments must supertypes of , b. see this answer excellent explanation on subject.
Comments
Post a Comment