0

زبان برنامه نویسی پرل

 
golami1223
golami1223
کاربر برنزی
تاریخ عضویت : آبان 1389 
تعداد پست ها : 683
محل سکونت : بوشهر

Blocks and iterators
پنج شنبه 2 دی 1389  7:53 AM

Blocks and iterators

هر دو سینتکس برای ایجاد یک بلوک کد:

{ puts "Hello, World!" }

do puts "Hello, World!" end 

ارسال پارامتر به یک بلاک تا یک closure شود:

# In an object instance variable, remember a block.
def remember(&b)
   @block = b
end

# Invoke the above method, giving it a block that takes a name.
remember {|name| puts "Hello, #{name}!"}

# When the time is right (for the object) -- call the closure!
@block.call("John")
# Prints "Hello, John!"

بازگشت closure از یک متد:

def foo(initial_value=0)
  var = initial_value
  return Proc.new {|x| var = x}, Proc.new { var }
end

setter, getter = foo
setter.call(21)
getter.call           # => 21

دادن جریان کنترل یک برنامه به یک بلوک که در هنگام فراخوانی ایجاد شده:

def a
   yield "hello"
end

# Invoke the above method, passing it a block.
a {|s| puts s}        # Prints: 'hello'
# Perhaps the following needs cleaning up.

# Breadth-first search
def bfs(e)                      # 'e' should be a block.
   q = []                       # Make an array.
   e.mark                       # 'mark' is a user-defined method. (??)
   yield e                      # Yield to the block.
   q.push e                     # Add the block to the array.
   while not q.empty?           # This could be made much more Ruby-like.
      u = q.shift
      u.edge_iterator do |v|
         if not v.marked?       # 'marked?' is a user-defined method.
            v.mark
            yield v
            q.push v
         end
      end  
   end
end
bfs(e) {|v| puts v}

ایجاد حلقه بر روی آرایه‌ها و enumoration‌ها با استفاده از بلوکها:

a = [1, 'hi', 3.14]
a.each {|item| puts item}                         # Prints each element
(3..6).each {|num| puts num}                      # Prints the numbers 3 through 6
[1,3,5].inject(0) {|sum, element| sum + element}  # Prints 9 (you can pass both a parameter and a block)

بلوکها با بسیاری از متدهای داخلی روبی کار می‌کنند:

File.open('file.txt', 'w+b') do |file|
   file.puts 'Wrote some text.'
end                             # File is automatically closed here

یا:

File.readlines('file.txt').each do |line|
   # Process each line, here.
end

استفاده از یک enumoration و یک بلوک برای جذر گرفتن اعداد 1 تا 10:

(1..10).collect {|x| x*x}    => [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
تشکرات از این پست
دسترسی سریع به انجمن ها