Showing posts with label iterator. Show all posts
Showing posts with label iterator. Show all posts

Sunday, February 8, 2009

Iterator in Icon

In Icon programming language, iterator is very powerful. As a result, Programming Language Pragmatics dedicates a sub section to explain it. The following shows the complete running code corresponding to the code snippets in the book.

procedure main()
write("=================================================")
every i := 1 to 10 by 2 do {
write(i)
}
write("=================================================")
every i := 1 + upto(' ', "a ss ss") do {
write(i)
}
write("=================================================")
i := 1
every write(i + upto(' ', "a ss ss"))
write("=================================================")
if 2 < 3 then {
write("2 < 3")
}
write("=================================================")
if (i := find("abc", "abcabcabc")) > 6 then {
write(i)
}
write("=================================================")
if (i := find("x", "xaax")) = find("x", "bxxx") then {
write(i)
}
end

The following code explains the description at the end of the sub section. It is If the expression following suspend contains an invocation of a generator, then the subroutine will suspend repeatedly, once for each generated value.

# suspend is followed by a value
procedure FollowedByValue()
i := 1
while i <= 3 do {
suspend i
i +:= 1
}
end

# suspend is followed by a generator expression
procedure FollowedByGenExpr()
suspend(1|2|3)
end

# suspend is followed by a generator function invocation
procedure FollowedByGenFuncInvocation()
suspend FollowedByValue()
end

procedure main()
write("=================================================")
every write(FollowedByValue())
write("=================================================")
every write(FollowedByGenExpr())
write("=================================================")
every write(FollowedByGenFuncInvocation())
end

Iterator in Ruby and Python

Unlike Java, both languages support real iterator not just iterator object. The following code shows how to create and use iterator in Python.

def from_1_to_5():
for i in [1, 2, 3, 4, 5]:
yield i

for num in from_1_to_5():
print num

The following code shows how to make it in Ruby. Desides a style similar to Python, Ruby can use iterator with block.

def iterator
for i in [1, 2, 3, 4, 5]
yield(i)
end
end

# invoke iterator in a way similar to Python
call_block do |num|
puts "#{num}"
end

# invoke iterator with the use of block
call_block { |num| puts "#{num}" }