Search code examples
crystal-lang

How to pass method to block in Crystal


How to pass plus into calculate method?

def calculate(&block : (Float64, Float64) -> Float64)
  block.call(1.1, 2.2)
end

def plus(a, b)
  a + b
end

calculate{|a, b| plus a, b}

This won't work

calculate ->plus
calculate &plus

P.S.

Another question, how to make it to work for all numbers? Not just Float64. This code won't compile and complain about requiring more specific type than Number

def calculate(&block : (Number, Number) -> Number)
  block.call(1, 2)
end

Ideally it would be nice to make it generalised so that typeof(block.call(1, 2)) => Int32 and typeof(block.call(1.1, 2.2)) => Float64


Solution

  • How to pass plus into calculate method?

    You're looking for

    calculate(&->plus(Float64, Float64))
    

    Where ->plus(Float64, Float64) returns a Proc. Mind that you have to specify the type of the arguments - see the section From methods in the reference manual.

    how to make it to work for all numbers?

    I'd look into forall - see the section on Free variables in the reference manual.