options.nim 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Nim Contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ##[
  10. This module implements types which encapsulate an optional value.
  11. A value of type `Option[T]` either contains a value `x` (represented as
  12. `some(x)`) or is empty (`none(T)`).
  13. This can be useful when you have a value that can be present or not. The
  14. absence of a value is often represented by `nil`, but that is not always
  15. available, nor is it always a good solution.
  16. Basic usage
  17. ===========
  18. Let's start with an example: a procedure that finds the index of a character
  19. in a string.
  20. ]##
  21. runnableExamples:
  22. proc find(haystack: string, needle: char): Option[int] =
  23. for i, c in haystack:
  24. if c == needle:
  25. return some(i)
  26. return none(int) # This line is actually optional,
  27. # because the default is empty
  28. let found = "abc".find('c')
  29. assert found.isSome and found.get() == 2
  30. ##[
  31. The `get` operation demonstrated above returns the underlying value, or
  32. raises `UnpackDefect` if there is no value. Note that `UnpackDefect`
  33. inherits from `system.Defect` and should therefore never be caught.
  34. Instead, rely on checking if the option contains a value with the
  35. `isSome <#isSome,Option[T]>`_ and `isNone <#isNone,Option[T]>`_ procs.
  36. Pattern matching
  37. ================
  38. .. note:: This requires the [fusion](https://github.com/nim-lang/fusion) package.
  39. [fusion/matching](https://nim-lang.github.io/fusion/src/fusion/matching.html)
  40. supports pattern matching on `Option`s, with the `Some(<pattern>)` and
  41. `None()` patterns.
  42. .. code-block:: nim
  43. {.experimental: "caseStmtMacros".}
  44. import fusion/matching
  45. case some(42)
  46. of Some(@a):
  47. assert a == 42
  48. of None():
  49. assert false
  50. assertMatch(some(some(none(int))), Some(Some(None())))
  51. ]##
  52. # xxx pending https://github.com/timotheecour/Nim/issues/376 use `runnableExamples` and `whichModule`
  53. when defined(nimHasEffectsOf):
  54. {.experimental: "strictEffects".}
  55. else:
  56. {.pragma: effectsOf.}
  57. import typetraits
  58. when defined(nimPreviewSlimSystem):
  59. import std/assertions
  60. when (NimMajor, NimMinor) >= (1, 1):
  61. type
  62. SomePointer = ref | ptr | pointer | proc
  63. else:
  64. type
  65. SomePointer = ref | ptr | pointer
  66. type
  67. Option*[T] = object
  68. ## An optional type that may or may not contain a value of type `T`.
  69. ## When `T` is a a pointer type (`ptr`, `pointer`, `ref` or `proc`),
  70. ## `none(T)` is represented as `nil`.
  71. when T is SomePointer:
  72. val: T
  73. else:
  74. val: T
  75. has: bool
  76. UnpackDefect* = object of Defect
  77. UnpackError* {.deprecated: "See corresponding Defect".} = UnpackDefect
  78. proc option*[T](val: sink T): Option[T] {.inline.} =
  79. ## Can be used to convert a pointer type (`ptr`, `pointer`, `ref` or `proc`) to an option type.
  80. ## It converts `nil` to `none(T)`. When `T` is no pointer type, this is equivalent to `some(val)`.
  81. ##
  82. ## **See also:**
  83. ## * `some proc <#some,T>`_
  84. ## * `none proc <#none,typedesc>`_
  85. runnableExamples:
  86. type
  87. Foo = ref object
  88. a: int
  89. b: string
  90. assert option[Foo](nil).isNone
  91. assert option(42).isSome
  92. result.val = val
  93. when T isnot SomePointer:
  94. result.has = true
  95. proc some*[T](val: sink T): Option[T] {.inline.} =
  96. ## Returns an `Option` that has the value `val`.
  97. ##
  98. ## **See also:**
  99. ## * `option proc <#option,T>`_
  100. ## * `none proc <#none,typedesc>`_
  101. ## * `isSome proc <#isSome,Option[T]>`_
  102. runnableExamples:
  103. let a = some("abc")
  104. assert a.isSome
  105. assert a.get == "abc"
  106. when T is SomePointer:
  107. assert not val.isNil
  108. result.val = val
  109. else:
  110. result.has = true
  111. result.val = val
  112. proc none*(T: typedesc): Option[T] {.inline.} =
  113. ## Returns an `Option` for this type that has no value.
  114. ##
  115. ## **See also:**
  116. ## * `option proc <#option,T>`_
  117. ## * `some proc <#some,T>`_
  118. ## * `isNone proc <#isNone,Option[T]>`_
  119. runnableExamples:
  120. assert none(int).isNone
  121. # the default is the none type
  122. discard
  123. proc none*[T]: Option[T] {.inline.} =
  124. ## Alias for `none(T) <#none,typedesc>`_.
  125. none(T)
  126. proc isSome*[T](self: Option[T]): bool {.inline.} =
  127. ## Checks if an `Option` contains a value.
  128. ##
  129. ## **See also:**
  130. ## * `isNone proc <#isNone,Option[T]>`_
  131. ## * `some proc <#some,T>`_
  132. runnableExamples:
  133. assert some(42).isSome
  134. assert not none(string).isSome
  135. when T is SomePointer:
  136. not self.val.isNil
  137. else:
  138. self.has
  139. proc isNone*[T](self: Option[T]): bool {.inline.} =
  140. ## Checks if an `Option` is empty.
  141. ##
  142. ## **See also:**
  143. ## * `isSome proc <#isSome,Option[T]>`_
  144. ## * `none proc <#none,typedesc>`_
  145. runnableExamples:
  146. assert not some(42).isNone
  147. assert none(string).isNone
  148. when T is SomePointer:
  149. self.val.isNil
  150. else:
  151. not self.has
  152. proc get*[T](self: Option[T]): lent T {.inline.} =
  153. ## Returns the content of an `Option`. If it has no value,
  154. ## an `UnpackDefect` exception is raised.
  155. ##
  156. ## **See also:**
  157. ## * `get proc <#get,Option[T],T>`_ with a default return value
  158. runnableExamples:
  159. assert some(42).get == 42
  160. doAssertRaises(UnpackDefect):
  161. echo none(string).get
  162. if self.isNone:
  163. raise newException(UnpackDefect, "Can't obtain a value from a `none`")
  164. result = self.val
  165. proc get*[T](self: Option[T], otherwise: T): T {.inline.} =
  166. ## Returns the content of the `Option` or `otherwise` if
  167. ## the `Option` has no value.
  168. runnableExamples:
  169. assert some(42).get(9999) == 42
  170. assert none(int).get(9999) == 9999
  171. if self.isSome:
  172. self.val
  173. else:
  174. otherwise
  175. proc get*[T](self: var Option[T]): var T {.inline.} =
  176. ## Returns the content of the `var Option` mutably. If it has no value,
  177. ## an `UnpackDefect` exception is raised.
  178. runnableExamples:
  179. var
  180. a = some(42)
  181. b = none(string)
  182. inc(a.get)
  183. assert a.get == 43
  184. doAssertRaises(UnpackDefect):
  185. echo b.get
  186. if self.isNone:
  187. raise newException(UnpackDefect, "Can't obtain a value from a `none`")
  188. return self.val
  189. proc map*[T](self: Option[T], callback: proc (input: T)) {.inline, effectsOf: callback.} =
  190. ## Applies a `callback` function to the value of the `Option`, if it has one.
  191. ##
  192. ## **See also:**
  193. ## * `map proc <#map,Option[T],proc(T)_2>`_ for a version with a callback
  194. ## which returns a value
  195. runnableExamples:
  196. var d = 0
  197. proc saveDouble(x: int) =
  198. d = 2 * x
  199. none(int).map(saveDouble)
  200. assert d == 0
  201. some(42).map(saveDouble)
  202. assert d == 84
  203. if self.isSome:
  204. callback(self.val)
  205. proc map*[T, R](self: Option[T], callback: proc (input: T): R): Option[R] {.inline, effectsOf: callback.} =
  206. ## Applies a `callback` function to the value of the `Option` and returns an
  207. ## `Option` containing the new value.
  208. ##
  209. ## If the `Option` has no value, `none(R)` will be returned.
  210. ##
  211. ## **See also:**
  212. ## * `map proc <#map,Option[T],proc(T)>`_
  213. ## * `flatMap proc <#flatMap,Option[T],proc(T)>`_ for a version with a
  214. ## callback that returns an `Option`
  215. runnableExamples:
  216. proc isEven(x: int): bool =
  217. x mod 2 == 0
  218. assert some(42).map(isEven) == some(true)
  219. assert none(int).map(isEven) == none(bool)
  220. if self.isSome:
  221. some[R](callback(self.val))
  222. else:
  223. none(R)
  224. proc flatten*[T](self: Option[Option[T]]): Option[T] {.inline.} =
  225. ## Remove one level of structure in a nested `Option`.
  226. ##
  227. ## **See also:**
  228. ## * `flatMap proc <#flatMap,Option[T],proc(T)>`_
  229. runnableExamples:
  230. assert flatten(some(some(42))) == some(42)
  231. assert flatten(none(Option[int])) == none(int)
  232. if self.isSome:
  233. self.val
  234. else:
  235. none(T)
  236. proc flatMap*[T, R](self: Option[T],
  237. callback: proc (input: T): Option[R]): Option[R] {.inline, effectsOf: callback.} =
  238. ## Applies a `callback` function to the value of the `Option` and returns the new value.
  239. ##
  240. ## If the `Option` has no value, `none(R)` will be returned.
  241. ##
  242. ## This is similar to `map`, with the difference that the `callback` returns an
  243. ## `Option`, not a raw value. This allows multiple procs with a
  244. ## signature of `A -> Option[B]` to be chained together.
  245. ##
  246. ## See also:
  247. ## * `flatten proc <#flatten,Option[Option[A]]>`_
  248. ## * `filter proc <#filter,Option[T],proc(T)>`_
  249. runnableExamples:
  250. proc doublePositives(x: int): Option[int] =
  251. if x > 0:
  252. some(2 * x)
  253. else:
  254. none(int)
  255. assert some(42).flatMap(doublePositives) == some(84)
  256. assert none(int).flatMap(doublePositives) == none(int)
  257. assert some(-11).flatMap(doublePositives) == none(int)
  258. map(self, callback).flatten()
  259. proc filter*[T](self: Option[T], callback: proc (input: T): bool): Option[T] {.inline, effectsOf: callback.} =
  260. ## Applies a `callback` to the value of the `Option`.
  261. ##
  262. ## If the `callback` returns `true`, the option is returned as `some`.
  263. ## If it returns `false`, it is returned as `none`.
  264. ##
  265. ## **See also:**
  266. ## * `flatMap proc <#flatMap,Option[A],proc(A)>`_
  267. runnableExamples:
  268. proc isEven(x: int): bool =
  269. x mod 2 == 0
  270. assert some(42).filter(isEven) == some(42)
  271. assert none(int).filter(isEven) == none(int)
  272. assert some(-11).filter(isEven) == none(int)
  273. if self.isSome and not callback(self.val):
  274. none(T)
  275. else:
  276. self
  277. proc `==`*[T](a, b: Option[T]): bool {.inline.} =
  278. ## Returns `true` if both `Option`s are `none`,
  279. ## or if they are both `some` and have equal values.
  280. runnableExamples:
  281. let
  282. a = some(42)
  283. b = none(int)
  284. c = some(42)
  285. d = none(int)
  286. assert a == c
  287. assert b == d
  288. assert not (a == b)
  289. when T is SomePointer:
  290. a.val == b.val
  291. else:
  292. (a.isSome and b.isSome and a.val == b.val) or (a.isNone and b.isNone)
  293. proc `$`*[T](self: Option[T]): string =
  294. ## Get the string representation of the `Option`.
  295. runnableExamples:
  296. assert $some(42) == "some(42)"
  297. assert $none(int) == "none(int)"
  298. if self.isSome:
  299. when defined(nimLagacyOptionsDollar):
  300. result = "Some("
  301. else:
  302. result = "some("
  303. result.addQuoted self.val
  304. result.add ")"
  305. else:
  306. when defined(nimLagacyOptionsDollar):
  307. result = "None[" & name(T) & "]"
  308. else:
  309. result = "none(" & name(T) & ")"
  310. proc unsafeGet*[T](self: Option[T]): lent T {.inline.}=
  311. ## Returns the value of a `some`. The behavior is undefined for `none`.
  312. ##
  313. ## **Note:** Use this only when you are **absolutely sure** the value is present
  314. ## (e.g. after checking with `isSome <#isSome,Option[T]>`_).
  315. ## Generally, using the `get proc <#get,Option[T]>`_ is preferred.
  316. assert self.isSome
  317. result = self.val