options.nim 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. import typetraits
  54. when (NimMajor, NimMinor) >= (1, 1):
  55. type
  56. SomePointer = ref | ptr | pointer | proc
  57. else:
  58. type
  59. SomePointer = ref | ptr | pointer
  60. type
  61. Option*[T] = object
  62. ## An optional type that may or may not contain a value of type `T`.
  63. ## When `T` is a a pointer type (`ptr`, `pointer`, `ref` or `proc`),
  64. ## `none(T)` is represented as `nil`.
  65. when T is SomePointer:
  66. val: T
  67. else:
  68. val: T
  69. has: bool
  70. UnpackDefect* = object of Defect
  71. UnpackError* {.deprecated: "See corresponding Defect".} = UnpackDefect
  72. proc option*[T](val: sink T): Option[T] {.inline.} =
  73. ## Can be used to convert a pointer type (`ptr`, `pointer`, `ref` or `proc`) to an option type.
  74. ## It converts `nil` to `none(T)`. When `T` is no pointer type, this is equivalent to `some(val)`.
  75. ##
  76. ## **See also:**
  77. ## * `some proc <#some,T>`_
  78. ## * `none proc <#none,typedesc>`_
  79. runnableExamples:
  80. type
  81. Foo = ref object
  82. a: int
  83. b: string
  84. assert option[Foo](nil).isNone
  85. assert option(42).isSome
  86. result.val = val
  87. when T isnot SomePointer:
  88. result.has = true
  89. proc some*[T](val: sink T): Option[T] {.inline.} =
  90. ## Returns an `Option` that has the value `val`.
  91. ##
  92. ## **See also:**
  93. ## * `option proc <#option,T>`_
  94. ## * `none proc <#none,typedesc>`_
  95. ## * `isSome proc <#isSome,Option[T]>`_
  96. runnableExamples:
  97. let a = some("abc")
  98. assert a.isSome
  99. assert a.get == "abc"
  100. when T is SomePointer:
  101. assert not val.isNil
  102. result.val = val
  103. else:
  104. result.has = true
  105. result.val = val
  106. proc none*(T: typedesc): Option[T] {.inline.} =
  107. ## Returns an `Option` for this type that has no value.
  108. ##
  109. ## **See also:**
  110. ## * `option proc <#option,T>`_
  111. ## * `some proc <#some,T>`_
  112. ## * `isNone proc <#isNone,Option[T]>`_
  113. runnableExamples:
  114. assert none(int).isNone
  115. # the default is the none type
  116. discard
  117. proc none*[T]: Option[T] {.inline.} =
  118. ## Alias for `none(T) <#none,typedesc>`_.
  119. none(T)
  120. proc isSome*[T](self: Option[T]): bool {.inline.} =
  121. ## Checks if an `Option` contains a value.
  122. ##
  123. ## **See also:**
  124. ## * `isNone proc <#isNone,Option[T]>`_
  125. ## * `some proc <#some,T>`_
  126. runnableExamples:
  127. assert some(42).isSome
  128. assert not none(string).isSome
  129. when T is SomePointer:
  130. not self.val.isNil
  131. else:
  132. self.has
  133. proc isNone*[T](self: Option[T]): bool {.inline.} =
  134. ## Checks if an `Option` is empty.
  135. ##
  136. ## **See also:**
  137. ## * `isSome proc <#isSome,Option[T]>`_
  138. ## * `none proc <#none,typedesc>`_
  139. runnableExamples:
  140. assert not some(42).isNone
  141. assert none(string).isNone
  142. when T is SomePointer:
  143. self.val.isNil
  144. else:
  145. not self.has
  146. proc get*[T](self: Option[T]): lent T {.inline.} =
  147. ## Returns the content of an `Option`. If it has no value,
  148. ## an `UnpackDefect` exception is raised.
  149. ##
  150. ## **See also:**
  151. ## * `get proc <#get,Option[T],T>`_ with a default return value
  152. runnableExamples:
  153. assert some(42).get == 42
  154. doAssertRaises(UnpackDefect):
  155. echo none(string).get
  156. if self.isNone:
  157. raise newException(UnpackDefect, "Can't obtain a value from a `none`")
  158. result = self.val
  159. proc get*[T](self: Option[T], otherwise: T): T {.inline.} =
  160. ## Returns the content of the `Option` or `otherwise` if
  161. ## the `Option` has no value.
  162. runnableExamples:
  163. assert some(42).get(9999) == 42
  164. assert none(int).get(9999) == 9999
  165. if self.isSome:
  166. self.val
  167. else:
  168. otherwise
  169. proc get*[T](self: var Option[T]): var T {.inline.} =
  170. ## Returns the content of the `var Option` mutably. If it has no value,
  171. ## an `UnpackDefect` exception is raised.
  172. runnableExamples:
  173. var
  174. a = some(42)
  175. b = none(string)
  176. inc(a.get)
  177. assert a.get == 43
  178. doAssertRaises(UnpackDefect):
  179. echo b.get
  180. if self.isNone:
  181. raise newException(UnpackDefect, "Can't obtain a value from a `none`")
  182. return self.val
  183. proc map*[T](self: Option[T], callback: proc (input: T)) {.inline.} =
  184. ## Applies a `callback` function to the value of the `Option`, if it has one.
  185. ##
  186. ## **See also:**
  187. ## * `map proc <#map,Option[T],proc(T)_2>`_ for a version with a callback
  188. ## which returns a value
  189. runnableExamples:
  190. var d = 0
  191. proc saveDouble(x: int) =
  192. d = 2 * x
  193. none(int).map(saveDouble)
  194. assert d == 0
  195. some(42).map(saveDouble)
  196. assert d == 84
  197. if self.isSome:
  198. callback(self.val)
  199. proc map*[T, R](self: Option[T], callback: proc (input: T): R): Option[R] {.inline.} =
  200. ## Applies a `callback` function to the value of the `Option` and returns an
  201. ## `Option` containing the new value.
  202. ##
  203. ## If the `Option` has no value, `none(R)` will be returned.
  204. ##
  205. ## **See also:**
  206. ## * `map proc <#map,Option[T],proc(T)>`_
  207. ## * `flatMap proc <#flatMap,Option[T],proc(T)>`_ for a version with a
  208. ## callback that returns an `Option`
  209. runnableExamples:
  210. proc isEven(x: int): bool =
  211. x mod 2 == 0
  212. assert some(42).map(isEven) == some(true)
  213. assert none(int).map(isEven) == none(bool)
  214. if self.isSome:
  215. some[R](callback(self.val))
  216. else:
  217. none(R)
  218. proc flatten*[T](self: Option[Option[T]]): Option[T] {.inline.} =
  219. ## Remove one level of structure in a nested `Option`.
  220. ##
  221. ## **See also:**
  222. ## * `flatMap proc <#flatMap,Option[T],proc(T)>`_
  223. runnableExamples:
  224. assert flatten(some(some(42))) == some(42)
  225. assert flatten(none(Option[int])) == none(int)
  226. if self.isSome:
  227. self.val
  228. else:
  229. none(T)
  230. proc flatMap*[T, R](self: Option[T],
  231. callback: proc (input: T): Option[R]): Option[R] {.inline.} =
  232. ## Applies a `callback` function to the value of the `Option` and returns the new value.
  233. ##
  234. ## If the `Option` has no value, `none(R)` will be returned.
  235. ##
  236. ## This is similar to `map`, with the difference that the `callback` returns an
  237. ## `Option`, not a raw value. This allows multiple procs with a
  238. ## signature of `A -> Option[B]` to be chained together.
  239. ##
  240. ## See also:
  241. ## * `flatten proc <#flatten,Option[Option[A]]>`_
  242. ## * `filter proc <#filter,Option[T],proc(T)>`_
  243. runnableExamples:
  244. proc doublePositives(x: int): Option[int] =
  245. if x > 0:
  246. some(2 * x)
  247. else:
  248. none(int)
  249. assert some(42).flatMap(doublePositives) == some(84)
  250. assert none(int).flatMap(doublePositives) == none(int)
  251. assert some(-11).flatMap(doublePositives) == none(int)
  252. map(self, callback).flatten()
  253. proc filter*[T](self: Option[T], callback: proc (input: T): bool): Option[T] {.inline.} =
  254. ## Applies a `callback` to the value of the `Option`.
  255. ##
  256. ## If the `callback` returns `true`, the option is returned as `some`.
  257. ## If it returns `false`, it is returned as `none`.
  258. ##
  259. ## **See also:**
  260. ## * `flatMap proc <#flatMap,Option[A],proc(A)>`_
  261. runnableExamples:
  262. proc isEven(x: int): bool =
  263. x mod 2 == 0
  264. assert some(42).filter(isEven) == some(42)
  265. assert none(int).filter(isEven) == none(int)
  266. assert some(-11).filter(isEven) == none(int)
  267. if self.isSome and not callback(self.val):
  268. none(T)
  269. else:
  270. self
  271. proc `==`*[T](a, b: Option[T]): bool {.inline.} =
  272. ## Returns `true` if both `Option`s are `none`,
  273. ## or if they are both `some` and have equal values.
  274. runnableExamples:
  275. let
  276. a = some(42)
  277. b = none(int)
  278. c = some(42)
  279. d = none(int)
  280. assert a == c
  281. assert b == d
  282. assert not (a == b)
  283. when T is SomePointer:
  284. a.val == b.val
  285. else:
  286. (a.isSome and b.isSome and a.val == b.val) or (a.isNone and b.isNone)
  287. proc `$`*[T](self: Option[T]): string =
  288. ## Get the string representation of the `Option`.
  289. runnableExamples:
  290. assert $some(42) == "some(42)"
  291. assert $none(int) == "none(int)"
  292. if self.isSome:
  293. when defined(nimLagacyOptionsDollar):
  294. result = "Some("
  295. else:
  296. result = "some("
  297. result.addQuoted self.val
  298. result.add ")"
  299. else:
  300. when defined(nimLagacyOptionsDollar):
  301. result = "None[" & name(T) & "]"
  302. else:
  303. result = "none(" & name(T) & ")"
  304. proc unsafeGet*[T](self: Option[T]): lent T {.inline.}=
  305. ## Returns the value of a `some`. The behavior is undefined for `none`.
  306. ##
  307. ## **Note:** Use this only when you are **absolutely sure** the value is present
  308. ## (e.g. after checking with `isSome <#isSome,Option[T]>`_).
  309. ## Generally, using the `get proc <#get,Option[T]>`_ is preferred.
  310. assert self.isSome
  311. result = self.val