Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Enhancement] add iterator protocol for object #282

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

khchen
Copy link

@khchen khchen commented Jul 21, 2022

Object can be used as iterator if _next and _value is defined. Similar to wren's iterator protocal. Example 1:

class Countup
  def _init(first, last, step)
    self.first = first
    self.last = last
    self.step = step
  end

  def _next(iter)
    if iter == null then return self.first end
    iter += self.step
    if iter > self.last then iter = null end
    return iter
  end

  def _value(iter)
    return iter
  end
end

for i in Countup(0, 10, 2)
  print(i)
end

Output:

0
2
4
6
8
10

Example 2:

class Node
  def _init(val)
    self.val = val
    self.next = null
  end

  def _str()
    return "(${self.val})"
  end
end

class LinkedList
  def _init()
    self.head = null
  end

  def append(node)
    if self.head == null
      self.head = node
    else
      last = self.head
      while last.next do last = last.next end
      last.next = node
    end
  end

  def _next(iter)
    if iter == null then return self.head end
    return iter.next
  end

  def _value(iter)
    return iter
  end
end

ll = LinkedList()
ll.append(Node(4))
ll.append(Node(6))
ll.append(Node(3))
ll.append(Node(9))

for n in ll
  print(n)
end

Output:

(4)
(6)
(3)
(9)

Example 3:

class StringIter
  def _init(text)
    self.text = text
  end

  def _next(iter)
    if iter == null then return 0 end
    iter += 1
    if iter >= self.text.length then iter = null end
    return iter
  end

  def _value(iter)
    return self.text[iter]
  end
end

for c in StringIter("hello")
  print(c)
end

Output:

h
e
l
l
o

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant