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

No comments: