fork download
  1. import java.lang.*;
  2. import java.io.*;
  3.  
  4. class JavaTypeClasses {
  5. // class Num t where ...
  6. public interface Num<T> {
  7. T add(T a, T b);
  8. T mul(T a, T b);
  9. }
  10.  
  11. // instance Num Int where...
  12. public static final class NumInt implements Num<Integer>{
  13. static final NumInt typeClass = new NumInt();
  14.  
  15. public Integer add(Integer a, Integer b) {
  16. return a + b;
  17. }
  18.  
  19. public Integer mul(Integer a, Integer b) {
  20. return a * b;
  21. }
  22. }
  23.  
  24. // instance Num Double where...
  25. public static final class NumDouble implements Num<Double> {
  26. static final NumDouble typeClass = new NumDouble();
  27.  
  28. public Double add(Double a, Double b) {
  29. return a + b;
  30. }
  31.  
  32. public Double mul(Double a, Double b) {
  33. return a * b;
  34. }
  35. }
  36.  
  37. // Num a => a -> a
  38. public static <T> T times2(Num<T> num, T x) {
  39. return num.add(x, x);
  40. }
  41.  
  42. // Num a => a -> a
  43. public static <T> T square(Num<T> num, T x) {
  44. return num.mul(x, x);
  45. }
  46.  
  47. public static void main (String[] args) throws java.lang.Exception
  48. {
  49. Integer intSix = times2(NumInt.typeClass, Integer.valueOf(3));
  50. Integer intNine = square(NumInt.typeClass, Integer.valueOf(3));
  51. Double doubleSix = times2(NumDouble.typeClass, Double.valueOf(3));
  52. Double doubleNine = square(NumDouble.typeClass, Double.valueOf(3));
  53. System.out.println(intSix);
  54. System.out.println(intNine);
  55. System.out.println(doubleSix);
  56. System.out.println(doubleNine);
  57. }
  58. }
Success #stdin #stdout 0.1s 320320KB
stdin
Standard input is empty
stdout
6
9
6.0
9.0