Search code examples
crystal-lang

What is a proc in 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?


Solution

  • 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