Search code examples
crystal-lang

Crystal lang curried


I try to create curried add proc in Crystal. How make this example to work?

semi_curry = ->(f: Proc(Int32, Int32)) { ->(a: Int32) { ->(b: Int32) { f.call(a, b) } } }

add = ->(a: Int32, b: Int32) {a + b}

p semi_curry(add).call(5).call(6)

https://play.crystal-lang.org/#/r/3r0g

I get error

no overload matches 'Proc(Int32, Int32)#call' with types Int32, Int32 Overloads are: - Proc(T, R)#call(*args : *T)


Solution

  • From the proc documentation, Proc(Int32, Int32) is a proc that takes one Int32 and returns one Int32. You mean to use Proc(Int32, Int32, Int32). Also, you need to use semi_curry.call(add).call(5).call(6).

    semi_curry = ->(f: Proc(Int32, Int32, Int32)) { ->(a: Int32) { ->(b: Int32) { f.call(a, b) } } }
    
    add = ->(a: Int32, b: Int32) {a + b}
    
    p semi_curry.call(add).call(5).call(6)
    

    https://play.crystal-lang.org/#/r/3r0m

    If you're looking to curry a proc in your application, instead of as a learning exercise, you should use Proc#partial instead.