tinyevil

Untitled

May 22nd, 2019
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. struct Rect {
  2. var width height: number;
  3. }
  4.  
  5. struct Circle {
  6. var radius: number;
  7. }
  8.  
  9. trait Shaped[T] {
  10. function get_area(value: ref T): number;
  11. }
  12.  
  13. @instance
  14. trait Shaped[Rect] {
  15. function get_area(value: Rect): number {
  16. return value.width * value.height;
  17. }
  18. }
  19.  
  20. @instance
  21. trait Shaped[Circle] {
  22. function get_area(value: Circle): number {
  23. return value.radius * value.radius * 3.1415;
  24. }
  25. }
  26.  
  27. // Here starts the fun part
  28. struct Shape[@erase T] {
  29. trait Shaped[T];
  30. var val: T;
  31. }
  32.  
  33. var shape: Shape[Circle] = {
  34. val = {
  35. radius=20
  36. // trait is automatic
  37. }
  38. };
  39. // `shape` acts exactly as if no @erase annotation
  40. // if we omit the type parameter, Shape becomes sizeless type
  41. // ref Shape is fair game
  42. var some_shape: ref Shape;
  43. some_shape = &shape; // this (type erasure) is allowed
  44. // this is allowed - some_shape.trait is used as an implementation
  45. get_area(some_shape.val);
Add Comment
Please, Sign In to add comment