Question: How do I dispatch the appropriate iterator for an subclassed object?
The following is a simple exemplar to clarify: (in the real world where would be many more subclass types)
We have two objects: (one and two) which are inherited from a common class (Number) Both object types (Odd and Even) support a type specific iterator (sample)
Nim
import sequtils
type
Number = object of RootObj
Odd = object of Number
Even = object of Number
iterator sample(number: Number): int =
for i in [1, 2, 3]:
yield i
iterator sample(number: Odd): int =
for i in [1, 3, 5]:
yield i
iterator sample(number: Even): int =
for i in [0, 2, 4]:
yield i
var
number: Number
even: Even
odd: Odd
echo "Number: ", sample(number).toSeq
echo "Odd: ", sample(odd).toSeq
echo "Even: ", sample(even).toSeq
let list = [number, odd, even]
echo "\nList type: ", list.type
for item in list:
echo "----"
echo "Item type: ", item.type
if item of Number: echo "- Is a Number"
if item of Odd: echo "- Is an Odd"
if item of Even: echo "- Is an Even"
# FINALLY the question :-)
# - How do I dispatch the appropriate iterator for each item in the list?
# ( without hardcoding the dispatch )
#
# - Compiling with the following two lines not commented out gives:
# Error: undeclared field: 'sample' for type test.Number
# for item in list:
# echo item.sample
Thanks for the quick response. Not the answer I was hoping for for but we don't want to shoot the message :-)
Followup questions:
Try a
import sequtils
type
Number = object of RootObj
Odd = object of Number
Even = object of Number
method sample(number: Number): iterator(): int =
result = iterator(): int =
for i in [1, 2, 3]:
yield i
method sample(number: Odd): iterator(): int =
result = iterator(): int =
for i in [1, 3, 5]:
yield i
method sample(number: Even): iterator(): int =
result = iterator(): int =
for i in [0, 2, 4]:
yield i
let list = [number, odd, even]
for item in list:
let x = item.sample
echo x()
echo x()
Thanks Calonger
Very clever! Wrapping the non-dispatchable iterator in a dispatchable method makes so much sense.