Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an anonymous function to the pipe in Elixir

Tags:

elixir

I'd like to write the code like this:

def boundary do   :crypto.rand_bytes(8)   |> Base.encode16   |> &("--------FormDataBoundary" <> &1) end 

But it doesn't work.

like image 642
ruisin Avatar asked Jul 06 '14 08:07

ruisin


People also ask

How do you call anonymous using Elixir?

To invoke an anonymous function, call it by the assigned name and add . between the name and arguments.

What does the pipe operator do in Elixir?

The pipe operator is the main operator for function composition in Elixir. It takes the result of the expression before it and passes it as the first argument of the following expression. Pipes replace nested function calls like foo(bar(baz)) with foo |> bar |> baz .


2 Answers

It will look bit weird but must work:

def boundary do   :crypto.rand_bytes(8)   |> Base.encode16   |> (&("--------FormDataBoundary" <> &1)).() end 
like image 90
couchemar Avatar answered Oct 02 '22 15:10

couchemar


Related: if the "anonymous" function has been assigned to a variable, you can pipe to it like this:

def boundary do   add_marker = fn (s) ->     "--------FormDataBoundary" <> s   end    :crypto.rand_bytes(8)   |> Base.encode16   |> add_marker.() end 
like image 30
Nathan Long Avatar answered Oct 02 '22 17:10

Nathan Long