tspec.nim 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. discard """
  2. output: '''4
  3. 0
  4. 4
  5. 4
  6. 1
  7. 2
  8. 3
  9. yes int
  10. string int'''
  11. joinable: false
  12. """
  13. import hashes
  14. type
  15. Comparable = concept # no T, an atom
  16. proc cmp(a, b: Self): int
  17. ToStringable = concept
  18. proc `$`(a: Self): string
  19. Hashable = concept ## the most basic of identity assumptions
  20. proc hash(x: Self): int
  21. proc `==`(x, y: Self): bool
  22. Swapable = concept
  23. proc swap(x, y: var Self)
  24. proc h(x: Hashable) =
  25. echo x
  26. h(4)
  27. when true:
  28. proc compare(a: Comparable) =
  29. echo cmp(a, a)
  30. compare(4)
  31. proc dollar(x: ToStringable) =
  32. echo x
  33. when true:
  34. dollar 4
  35. dollar "4"
  36. #type D = distinct int
  37. #dollar D(4)
  38. when true:
  39. type
  40. Iterable[Ix] = concept
  41. iterator items(c: Self): Ix
  42. proc g[Tu](it: Iterable[Tu]) =
  43. for x in it:
  44. echo x
  45. g(@[1, 2, 3])
  46. proc hs(x: Swapable) =
  47. var y = x
  48. swap y, y
  49. hs(4)
  50. type
  51. Indexable[T] = concept # has a T, a collection
  52. proc `[]`(a: Self; index: int): T # we need to describe how to infer 'T'
  53. # and then we can use the 'T' and it must match:
  54. proc `[]=`(a: var Self; index: int; value: T)
  55. proc len(a: Self): int
  56. proc indexOf[T](a: Indexable[T]; value: T) =
  57. echo "yes ", T
  58. block:
  59. var x = @[1, 2, 3]
  60. indexOf(x, 4)
  61. import tables, typetraits
  62. type
  63. Dict[K, V] = concept
  64. proc `[]`(s: Self; k: K): V
  65. proc `[]=`(s: var Self; k: K; v: V)
  66. proc d[K2, V2](x: Dict[K2, V2]) =
  67. echo K2, " ", V2
  68. var x = initTable[string, int]()
  69. d(x)
  70. type Monoid = concept
  71. proc `+`(x, y: Self): Self
  72. proc z(t: typedesc[Self]): Self
  73. proc z(x: typedesc[int]): int = 0
  74. doAssert int is Monoid