Search code examples
functional-programmingjuliacurrying

A generic way to curry functions in Julia


What are some idiomatic ways to achieve function currying?

Eg. in Haskell:

times a b = a * b
-- This can then be used uncurried:
times 2 3     -- Result is 6
-- But there is also auto-currying:
(times 2) 3   -- This works too

In Julia, some built-ins support this:

<(8, 7)    # Result is false
<(7)(8)    # Same
7 |> <(8)  # Same

However, user-defined functions don't automatically have this functionality:

times(a, b) = a * b
times(2, 3)    # Result is 6
3 |> times(2)  # MethodError: no method matching times(::Int64)

I can manually define a one-argument version like this:

times(a) = b -> a * b

But my question is, is there a generic operator or function that achieves this and works for both user-defined and built-in functions?


Solution

  • why not use curry.jl

    times(a, b) = a * b
    times_curry = curry(times)
    times_curry(5)(2) ---> gives 10