tyaoption.nim 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. discard """
  2. output: '''some(str), some(5), none
  3. some(5!)
  4. some(10)
  5. 34'''
  6. """
  7. import strutils
  8. type Option[A] = object
  9. case isDefined*: bool
  10. of true:
  11. value*: A
  12. of false:
  13. nil
  14. proc some[A](value: A): Option[A] =
  15. Option[A](isDefined: true, value: value)
  16. proc none[A](): Option[A] =
  17. Option[A](isDefined: false)
  18. proc `$`[A](o: Option[A]): string =
  19. if o.isDefined:
  20. "some($1)" % [$o.value]
  21. else:
  22. "none"
  23. let x = some("str")
  24. let y = some(5)
  25. let z = none[int]()
  26. echo x, ", ", y, ", ", z
  27. proc intOrString[A : int | string](o: Option[A]): Option[A] =
  28. when A is int:
  29. some(o.value + 5)
  30. elif A is string:
  31. some(o.value & "!")
  32. else:
  33. o
  34. #let a1 = intOrString(none[String]())
  35. let a2 = intOrString(some("5"))
  36. let a3 = intOrString(some(5))
  37. #echo a1
  38. echo a2
  39. echo a3
  40. # bug #10033
  41. type
  42. Token = enum
  43. Int,
  44. Float
  45. Base = ref object of RootObj
  46. case token: Token
  47. of Int:
  48. bInt: int
  49. of Float:
  50. bFloat: float
  51. Child = ref object of Base
  52. let c = new Child
  53. c.token = Int
  54. c.bInt = 34
  55. echo c.bInt