Saturday, January 15, 2011

Studying F# : Sequence

F#'s Sequence (seq{ }) instantiates "The way to generate sequential values", not sequential values themselves. The corresponding paradigm in Ruby 1.9 can be implemented with Enumerator. Let's check each codes.

In F#

open System
let oneUptoTen = seq {
    for i = 1 to 10 do
        Console.WriteLine("{0} is generated", i)
        yield i
}
let oneUptoTenEnum = oneUptoTen.GetEnumerator()
while oneUptoTenEnum.MoveNext() do
    Console.WriteLine(oneUptoTenEnum.Current)


In Ruby 1.9

one_upto_ten = proc { |yielder|
  1.upto(10) do |i|
    puts "#{i} is generated"
    yielder << i
  end
}
one_upto_ten_enum = Enumerator.new(&one_upto_ten)
loop do
  puts one_upto_ten_enum.next
end


Outputs are below:
1 is generated
1
2 is generated
2
3 is generated
3
4 is generated
4
5 is generated
5
6 is generated
6
7 is generated
7
8 is generated
8
9 is generated
9
10 is generated
10

No comments:

Post a Comment