Crystal lang Crystal如何检查函数中是否给出了块参数

Crystal lang Crystal如何检查函数中是否给出了块参数,crystal-lang,Crystal Lang,假设一个定义如下的函数: def composition(text : String, k : Int32) : Array(String) kmers = Array(String).new (0 .. text.size - k).each do |i| kmers << text[i, k] yield text[i, k] end return kmers end # if you want to be explicit (makes no

假设一个定义如下的函数:

def composition(text : String, k : Int32) : Array(String)
  kmers = Array(String).new
  (0 .. text.size - k).each do |i|
    kmers << text[i, k]
    yield text[i, k]
  end
  return kmers
end
# if you want to be explicit (makes no difference):
# def composition(text : String, k : Int32, &block)
def composition(text : String, k : Int32)
  (0 .. text.size - k).each do |i|
    yield text[i, k]
  end
end

def composition(text : String, k : Int32) : Array(String)
  kmers = [] of String
  composition(text, k) do |s|
    kmers << s
  end
  return kmers
end
def组合(text:String,k:Int32):数组(String)
kmers=数组(字符串)。新建
(0..text.size-k)。每个do|i|

kmers这样的检查是不可能的,因为接受块的方法(使用
yield
anywhere)只是具有不同的签名。但这也意味着你不需要检查,只需要做如下两种方法:

def composition(text : String, k : Int32) : Array(String)
  kmers = Array(String).new
  (0 .. text.size - k).each do |i|
    kmers << text[i, k]
    yield text[i, k]
  end
  return kmers
end
# if you want to be explicit (makes no difference):
# def composition(text : String, k : Int32, &block)
def composition(text : String, k : Int32)
  (0 .. text.size - k).each do |i|
    yield text[i, k]
  end
end

def composition(text : String, k : Int32) : Array(String)
  kmers = [] of String
  composition(text, k) do |s|
    kmers << s
  end
  return kmers
end
#如果您想要明确(没有区别):
#def合成(文本:字符串、k:Int32和块)
def合成(文本:字符串,k:Int32)
(0..text.size-k)。每个do|i|
产生文本[i,k]
结束
结束
def组合(text:String,k:Int32):数组(String)
kmers=[]个字符串
作文(课文,k)do|s|

kmers处理OP的用例,但仍然存在一个问题,即是否有可能确定是否已通过一个块。有?我认为不是,因为调用一个需要一个没有块的块的函数会导致编译时错误;因此,甚至无法在运行时挽救异常。