ttuple.nim 880 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. discard """
  2. output: '''5.0 10.0'''
  3. """
  4. type
  5. MyOpt[T] = object
  6. case has: bool:
  7. of true: val: T
  8. of false: nil
  9. MyVal = object
  10. f: ptr float
  11. proc `=destroy`(x: var MyVal) =
  12. if x.f != nil:
  13. dealloc(x.f)
  14. proc `=sink`(x1: var MyVal, x2: Myval) =
  15. if x1.f != x2.f:
  16. `=destroy`(x1)
  17. x1.f = x2.f
  18. proc `=`(x1: var MyVal, x2: Myval) =
  19. if x1.f != x2.f:
  20. `=destroy`(x1)
  21. x1.f = create(float)
  22. x1.f[] = x2.f[]
  23. proc newVal(x: float): MyVal =
  24. result.f = create(float)
  25. result.f[] = x
  26. template getIt[T, R](self: MyOpt[T], body: untyped, default: R): R =
  27. if self.has:
  28. template it: untyped {.inject.} = self.val
  29. body
  30. else:
  31. default
  32. proc myproc(h: MyOpt[float]) =
  33. let (a, b) = h.getIt((newVal(it), newVal(it * 2)), (newVal(1.0), newVal(1.0)))
  34. echo a.f[], " ", b.f[]
  35. let h = MyOpt[float](has: true, val: 5.0)
  36. myproc(h)