The question is, how to create a python like iterator in Kotlin.
Consider this python code that parses string into substrings:
def parse(strng, idx=1):
lst = []
for i, c in itermarks(strng, idx):
if c == '}':
lst.append(strng[idx:i-1])
break
elif c == '{':
sublst, idx = parse(strng, i+1)
lst.append(sublst)
else:
lst.append(strng[idx:i-1])
idx = i+1
return lst, i
>>>res,resl = parse('{ a=50 , b=75 , { e=70, f=80 } }')
>>>print(resl)
>>>[' a=50', ' b=75', [' e=7', ' f=80'], '', ' f=80']
This is a play example just to illustrate a python iterator:
def findany(strng, idx, chars):
""" to emulate 'findany' in kotlin """
while idx < len(strng) and strng[idx] not in chars:
idx += 1
return idx
def itermarks(strng, idx=0):
while True:
idx = findany(strng, idx, ',{}"')
if idx >= len(strng):
break
yield idx, strng[idx]
if strng[idx] == '}':
break
idx += 1
Kotlin has iterators and generators, and as I understand it there can only be one per type. My idea is to define a type with a generator and instance that type. So the for loop from 'parse' (above) would look like this :
for((i,c) in IterMarks(strng){ ...... }
But how do i define the generator, and what is the best idiom.