diff options
author | Timothee Cour <timothee.cour2@gmail.com> | 2021-04-11 07:25:41 -0500 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-04-11 14:25:41 +0200 |
commit | ceadf54d7649b8cc728fd0b6df966bbf28bf55bd (patch) | |
tree | 4106775d096082764b3c614ee74b44e21c23988a /doc | |
parent | a5b30c94c2dcd0f17b37685d9ce96eee959ba554 (diff) | |
download | Nim-ceadf54d7649b8cc728fd0b6df966bbf28bf55bd.tar.gz |
iterable[T] (#17196)
* fix failing test toSeq in manual which now works * changelog * reject proc fn(a: iterable) * add iterable to spec * remove MCS/UFCS limitation that now works
Diffstat (limited to 'doc')
-rw-r--r-- | doc/manual.rst | 43 |
1 files changed, 25 insertions, 18 deletions
diff --git a/doc/manual.rst b/doc/manual.rst index 1325d1c5f..ea444a0ac 100644 --- a/doc/manual.rst +++ b/doc/manual.rst @@ -2645,6 +2645,28 @@ Varargs matching See `Varargs <#types-varargs>`_. +iterable +-------- + +A called `iterator` yielding type `T` can be passed to a template or macro via +a parameter typed as `untyped` (for unresolved expressions) or the type class +`iterable` or `iterable[T]` (after type checking and overload resolution). + +.. code-block:: nim + iterator iota(n: int): int = + for i in 0..<n: yield i + + template toSeq2[T](a: iterable[T]): seq[T] = + var ret: seq[T] + assert a.typeof is T + for ai in a: ret.add ai + ret + + assert iota(3).toSeq2 == @[0, 1, 2] + assert toSeq2(5..7) == @[5, 6, 7] + assert not compiles(toSeq2(@[1,2])) # seq[int] is not an iterable + assert toSeq2(items(@[1,2])) == @[1, 2] # but items(@[1,2]) is + Statements and expressions ========================== @@ -4351,6 +4373,9 @@ would. For example: for i in toItr(recCountDown(6)): # Emits: 6 5 4 3 2 1 echo i + +See also see `iterable <#overloading-resolution-iterable>`_ for passing iterators to templates and macros. + Converters ========== @@ -5591,24 +5616,6 @@ is used to invoke templates/macros: unknownIdentifier.declareVar -Another common example is this: - -.. code-block:: nim - :test: "nim c $1" - :status: 1 - - from std/sequtils import toSeq - - iterator something: string = - yield "Hello" - yield "World" - - var info = something().toSeq - -The problem here is that the compiler already decided that `something()` as -an iterator is not callable in this context before `toSeq` gets its -chance to convert it into a sequence. - It is also not possible to use fully qualified identifiers with module symbol in method call syntax. The order in which the dot operator binds to symbols prohibits this. |