Crystal Lang 中的过程是什么?

What is a proc in Crystal Lang?

我阅读了组织网站上 Crystal 语言书中关于 Procs 的文档。 proc到底是什么?我知道你定义了参数和 return 类型,并使用调用方法来调用 proc,这让我认为它是一个函数。但是为什么要使用 proc?它有什么用?

你不能将方法传递给其他方法(但你可以将过程传递给方法),方法不能return其他方法(但它们可以return过程)。

Proc 还从定义范围内捕获变量:

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

一个强大的功能是将块转换为 Proc 并将其传递给方法,因此您可以 forward it:

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

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

此外,正如@Johannes Müller 评论的那样,Proc 可以用作 closure:

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

minus_20 = minus(20)
minus_20.call(7) # => 13

语言参考实际上很好地解释了 Proc

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

所以是的,proc 本质上就像一个函数。与普通块相比,它本质上包含对块的引用,因此它可以存储和传递,还提供闭包。

Proc 只是一个没有名字的 function/method。您可以将它作为一个变量传递,它可以引用它封闭范围内的变量(它是一个闭包)。它们通常用作将方法块作为变量传递的一种方式。