【问题标题】:Is it possible to pass a Proc into a function?是否可以将 Proc 传递给函数?
【发布时间】:2021-09-07 00:12:56
【问题描述】:

我正在尝试将 Ruby 的函数组合运算符 << 实现到 Crystal 的 proc 中。在 Ruby 中,这似乎很简单。

  def << block
    proc { |*args| self.call( block.to_proc.call(*args) ) }
  end
end

我尝试过做类似的事情。

struct Proc
  def <<(&block)
    Proc.new { |*args, blk| call(block.call(*args, blk)) }
  end
end

我试过用一个简单的加法器和子函数来测试它

def add(x : Int32)
  x + 1
end

def sub(x : Int32)
  x - 1
end

但是,我收到了这个错误。 Error: wrong number of arguments for 'Proc(Int32, Int32)#&lt;&lt;' (given 1, expected 0)

我还尝试更改 &lt;&lt; 以接收 proc,但这也会导致 expected block type to be a function type, not Proc(*T, R)

我对这门语言有点陌生,所以我不太确定我缺少哪些知识来理解为什么这不起作用。

【问题讨论】:

    标签: crystal-lang


    【解决方案1】:

    您收到此错误是因为未指定 ProcProc 类型是泛型类型,需要使用描述其参数类型和返回类型的特定泛型参数进行实例化。

    您可以通过一个最小的示例看到相同的行为:

    Proc.new { 1 } # Error: expected block type to be a function type, not Proc(*T, R)
    

    当然,错误信息不是很能说明问题。


    您尝试实现的工作示例如下所示:

    struct Proc
      def <<(block : Proc(*U, V)) forall U, V
        Proc(*T, V).new { |arg| call(block.call(arg)) }
      end
    end
    
    def add(x : Int32)
      x + 1
    end
     
    def sub(x : Int32)
      x - 1
    end
    
    x = ->add(Int32) << ->sub(Int32)
    p! x.call(10)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-08
      • 1970-01-01
      • 2013-10-08
      • 1970-01-01
      • 2021-07-29
      • 2015-05-11
      • 2021-11-11
      相关资源
      最近更新 更多