Skip to content

Instantly share code, notes, and snippets.

@rahulmutt
Last active September 12, 2017 04:34
Show Gist options
  • Save rahulmutt/6c017de7e21d10d2eaff6558d347f5ae to your computer and use it in GitHub Desktop.
Save rahulmutt/6c017de7e21d10d2eaff6558d347f5ae to your computer and use it in GitHub Desktop.
Polymorphism in Eta via Type Erasure
public static class id extends Function {
public Closure enter(StgContext context) {
// context.R(2) is the first argument of the function
// All id simply does is evaluate the argument -
// it cannot do much more!
return context.R(2).evaluate(context);
}
public int arity() { return 1; }
}
public static class showWithParens extends Function {
public Closure enter(StgContext context) {
// Dictionary for (Show a)
Closure showA = context.R(2);
Closure x = context.R(3);
// Thunk for (show x ++ ")")
Main.sat_s2D0 localsat_s2D0 = new Main.sat_s2D0(showA, x);
// Represents a lazy string: "("
Main.sat_s2CX localsat_s2CX = new Main.sat_s2CX();
// Evaluates ("(" ++ (show x ++ ")"))
return Base.zpzp().applyPP(context, localsat_s2CX, localsat_s2D0);
}
public int arity() { return 2; }
}
public static class showWithParensEx extends Function {
public Closure enter(StgContext context) {
Closure showable = context.R(2);
// Evaluate first argument
Closure localClosure2 = showable.evaluate(context);
// Cast to Showable data constructor
Main.ShowableD showable_eval = ((Main.ShowableD)localClosure2);
// Grab '(Show a)' typeclass dictionary from existential type
Closure showableDict = showable_eval.x1;
// Grab 'a' from Showable data constructor
Closure x = showable_eval.x2;
// Evaluatate 'show x'
context.R(2, showableDict);
return Show.show().enter(context).applyP(context, x);
}
public int arity() { return 1; }
}
public static class showWith extends Function {
public Closure enter(StgContext context) {
Closure f = context.R(2);
// sat_s2CQ represents the expression for "SomeString"
Main.sat_s2CQ someString = new Main.sat_s2CQ();
// evaluate f "SomeString"
return f.applyP(context, someString);
}
public int arity() { return 1; }
}
-- Parametric Polymorphism
id :: a -> a
id x = x
-- Ad-hoc or bounded Polymorphism
showWithParens :: (Show a) => a -> String
showWithParens x = "(" ++ show x ++ ")"
-- Existential types
data Showable = Showable (forall a. (Show a) => a)
showWithParensEx :: Showable -> String
showWithParensEx (Showable x) = show x
-- Higher-rank function
showWith :: (forall a. a -> Int) -> Int
showWith f = f "SomeString"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment