Add example for pattern matching on options (#17120)

* Add example for pattern matching on options

* Use code-block

* Apply suggestions

* Use block comments

* Fix example
This commit is contained in:
konsumlamm
2021-02-22 11:16:15 +01:00
committed by GitHub
parent ef5303114c
commit 05711d95e0

View File

@@ -7,22 +7,24 @@
# distribution, for details about the copyright.
#
## This module implements types which encapsulate an optional value.
##
## A value of type `Option[T]` either contains a value `x` (represented as
## `some(x)`) or is empty (`none(T)`).
##
## This can be useful when you have a value that can be present or not. The
## absence of a value is often represented by `nil`, but that is not always
## available, nor is it always a good solution.
##
##
## Basic usage
## ===========
##
## Let's start with an example: a procedure that finds the index of a character
## in a string.
##
##[
This module implements types which encapsulate an optional value.
A value of type `Option[T]` either contains a value `x` (represented as
`some(x)`) or is empty (`none(T)`).
This can be useful when you have a value that can be present or not. The
absence of a value is often represented by `nil`, but that is not always
available, nor is it always a good solution.
Basic usage
===========
Let's start with an example: a procedure that finds the index of a character
in a string.
]##
runnableExamples:
proc find(haystack: string, needle: char): Option[int] =
for i, c in haystack:
@@ -34,11 +36,37 @@ runnableExamples:
let found = "abc".find('c')
assert found.isSome and found.get() == 2
## The `get` operation demonstrated above returns the underlying value, or
## raises `UnpackDefect` if there is no value. Note that `UnpackDefect`
## inherits from `system.Defect` and should therefore never be caught.
## Instead, rely on checking if the option contains a value with the
## `isSome <#isSome,Option[T]>`_ and `isNone <#isNone,Option[T]>`_ procs.
##[
The `get` operation demonstrated above returns the underlying value, or
raises `UnpackDefect` if there is no value. Note that `UnpackDefect`
inherits from `system.Defect` and should therefore never be caught.
Instead, rely on checking if the option contains a value with the
`isSome <#isSome,Option[T]>`_ and `isNone <#isNone,Option[T]>`_ procs.
Pattern matching
================
.. note:: This requires the [fusion](https://github.com/nim-lang/fusion) package.
[fusion/matching](https://nim-lang.github.io/fusion/src/fusion/matching.html)
supports pattern matching on `Option`s, with the `Some(<pattern>)` and
`None()` patterns.
.. code-block:: nim
{.experimental: "caseStmtMacros".}
import fusion/matching
case some(42)
of Some(@a):
assert a == 42
of None():
assert false
assertMatch(some(some(none(int))), Some(Some(None())))
]##
# xxx pending https://github.com/timotheecour/Nim/issues/376 use `runnableExamples` and `whichModule`
import std/typetraits