Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a proc in Crystal Lang?

Tags:

crystal-lang

I read the documentation on Procs in the Crystal Language book on the organizations’s site. What exactly is a proc? I get that you define argument and return types and use a call method to call the proc which makes me think it’s a function. But why use a proc? What is it for?

like image 895
dkimot Avatar asked Mar 15 '18 05:03

dkimot


3 Answers

You cannot pass methods into other methods (but you can pass procs into methods), and methods cannot return other methods (but they can return procs).

Also Proc captures variables from the scope where it has been defined:

a = 1
b = 2

proc = ->{ a + b }

def foo(proc)
  bar(proc)
end

def bar(proc)
  a = 5
  b = 6
  1 + proc.call
end

puts bar(proc) # => 4

A powerful feature is to convert a block to Proc and pass it to a method, so you can forward it:

def int_to_int(&block : Int32 -> Int32)
  block
end

proc = int_to_int { |x| x + 1 }
proc.call(1) #=> 2

Also, as @Johannes Müller commented, Proc can be used as a closure:

def minus(num)
  ->(n : Int32) { num - n }
end

minus_20 = minus(20)
minus_20.call(7) # => 13
like image 186
WPeN2Ic850EU Avatar answered Oct 19 '22 13:10

WPeN2Ic850EU


The language reference explains Proc pretty well actually:

A Proc represents a function pointer with an optional context (the closure data).

So yes, a proc is essentially like a function. In contrast to a plain block, it essentially holds a reference to a block so it can be stored and passed around and also provides a closure.

like image 3
Johannes Müller Avatar answered Oct 19 '22 11:10

Johannes Müller


A Proc is simply a function/method without a name. You can pass it around as a variable, and it can refer to variables in it's enclosing scope (it's a closure). They are often used as a way of passing method blocks around as variables.

like image 3
Stephie Avatar answered Oct 19 '22 12:10

Stephie