Mathematica Asked by yode on January 31, 2021
I find that Mathematica has the iterator data structure. We can build some iterators like this:
GeneralUtilities`ConstantIterator[5]
GeneralUtilities`KeyValueIterator[<|a -> x, b -> y, c -> z|>]
GeneralUtilities`RangeIterator[9]
We can find all iterator functions with
Names["GeneralUtilities`*Iterator*"]
But I don’t know how to process the iterator, as Mathematica has no function like next
on Python:
>>> string='FhC'
>>> it=iter(string)
>>> next(it)
'F'
>>> next(it)
'h'
Michael E2’s answer clear this problem a lot,But I hope the DelegateIterator
, IteratorGraph
, JoinMapIterator
, SingletonIterator
, StreamIterator
, TerminatorIterator
and ToIterator
can be discussed still.
Such functions set up a one-time iterator, i.e. a GeneralUtilities`Iterator
. Its functionality may be inspected with
? GeneralUtilities`Iterator
and so forth. Except for a ConstantIterator
which always returns the same value (forever), they go sequentially through values until they return GeneralUtilities`IteratorExhausted
.
The main (if internal) utility is GeneralUtilities`PackageScope`PullIterator
:
foo = GeneralUtilities`KeyValueIterator[<|a -> x, b -> y, c -> z|>];
GeneralUtilities`PackageScope`PullIterator@foo
GeneralUtilities`PackageScope`PullIterator@foo
GeneralUtilities`PackageScope`PullIterator@foo
GeneralUtilities`PackageScope`PullIterator@foo
(*
a -> x
b -> y
c -> z
IteratorExhausted
*)
One can see from inspection with ?...
that one can do such things as Map
, Scan
, Fold
, Read
, etc., over iterators:
foo = GeneralUtilities`KeyValueIterator[<|a -> x, b -> y, c -> z|>];
Map[f, foo]
(* {f[a -> x], f[b -> y], f[c -> z]} *)
Normal
converts them to a list:
foo = GeneralUtilities`KeyValueIterator[<|a -> x, b -> y, c -> z|>];
Normal[foo]
(* {a -> x, b -> y, c -> z} *)
Other functionality can be inspected with ?
.
Answered by Michael E2 on January 31, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP