Partial Function Application In Elixir

So I’m trying to fill out my understanding of basic functional programming concepts in terms of Elixir and Erlang.  One concept that I wanted to know a bit more about is how Partial Function Application and Currying work in Elixir.  Especially given that the function signature of a function in Elixir includes its arity, it seems somewhat unlikely that Elixir would support currying and/or partial function application.  But a little bit of hacking turned up a nice surprise.  While Elixir may not support currying (I really cannot tell if it is supported or not) it does support partial function application which seems to be the main reason to concern one’s self with currying anyway.

Partial Function Application With Lambdas


multiply = &(&1 * &2)

timestwo = &(multiply.(&1,2))

Interestingly, using this technique you can set any number of parameters to a fixed value.  Consider this:


multiply4 = &(&1 * &2 * &3 * &4)

times20 = &(multiply4.(&1,&2,5,4))

Lest I be misunderstood, I wouldn’t advocate writing code like that; I’m just saying that it’s possible to do.

Partial Function Application With Modules


defmodule PaTest do
  def f1(n, m) do
    n * m
  end

  def f2(m) do
    f1(3,m)
  end
end

I hope this may save someone a bit of work.

5 responses

  1. Why would arity matter? Partial application would return a new function with it’s own arity. It’s no different than have anonymous functions.

Leave a comment