LionelMarco

LionelMarco

How to execute the quoted expression of an anonymous function?

I have a Plug with many functions that return a parameterized anonymous function, for example:


def scaling(vmin,vmax) do
  fn value ->
    cond do
      not is_number(value)   -> 0
      value <= vmin ->  vmin
      value > vmax ->  vmax
      true -> value
    end
  end
end

The code of the Plug

defmodule Plug.RouterDataProcessor do

  def init(opts), do: opts  
    def call(conn, opts) do
    case conn.private[:process] do
      nil -> conn
      tasks -> process(conn,tasks, opts[:on_error])
    end
  end

  def process(conn,tasks,on_error) do
    Enum.map(tasks,do_task(Map.get(conn.body_params,"items")  ))    
  end

  def do_task(data) do
    fn task ->
      Enum.map(data,fn value ->fd.(value) end)
    end
  end


def scaling(vmin,vmax) do
  fn value ->
    cond do
      not is_number(value)   -> 0
      value <= vmin ->  vmin
      value > vmax ->  vmax
      true -> value
    end
  end
end
end

end

The function is already declared inside the plug.

The function will be passed from the route to the plug,

So in the Route:


defmodule UsersRouter do
  use RouterHelpers
  use Plug.ErrorHandler

import Plug.RouterDataProcessor

plug :match
plug Plug.RouterDataProcessor, on_error: &UsersRouter.on_error_fn/2
plug :dispatch
import Plug.RouterDataProcessor


tasks=[scaling(0,100),group(1),sum(1),sort(2)] # Many function can be grouped in a list

post "/receive/", private: %{process: tasks} do
        # do something with data
	# then send response
	send_json(conn,  %{status: "success"})
end

end

But when compile get the error:
== Compilation error in file lib/routes/data_router.ex ==
** (ArgumentError) cannot escape #Function<1.72916727/1 in DataProcessor.scaling/2>. The supported values are: lists, tuples, maps, atoms, numbers, bitstrings

Then try to capture, but is a incorrect point because I need to capture the returned anonymous function.

My second attemp is use quote/unquote


def scaling(vmin,vmax) do
  quote do
     fn value ->
    cond do
      not is_number(value)   -> 0
      value <= unquote(vmin) -> unquote(vmin)
      value >  unquote(vmax) ->  unquote(vmax)
      true -> value
    end
  end
  end
end

But I can’t find how to execute the quoted expression


 def do_task(data) do
    fn task ->
      IO.inspect task # print the representation {:fn, [], ....
      # try to execute
      Enum.map(data,fn value ->task.(value) end)       
    end
  end

Give me:

** (Plug.Conn.WrapperError) ** (BadFunctionError) expected a function, got:{:fn, [], …

I does not know why have this problem because if I run all inside the “post”,
the code run ok.

post "/datapro/" do 
    send_json(conn,  %{ t:  process(conn,[scaling(5,25)],&UsersRouter.on_error_fn/2)})
end

I am newbie, so is good to resolve with the quoted aproach, or there is any better way ?
Is there any performance drawback when use AST representation ?

How can resolve it ?

Most Liked

al2o3cr

al2o3cr

quote returns the AST representation of the code put inside of it, but running that code would mean compiling it first. This is not the way.

The arguments passed to plug and related machinery are calculated at compile-time, but used at runtime. To do that, they need to be stored in the generated BEAM file (as one of the supported types).

There are a few other places in the ecosystem where this kind of restriction happens, and the typical approach is to use MFA tuples - a tuple like {UserRouterHelpers, :scaling, [10, 42]} of a module, a function name, and a list of arguments. Your process function might be written as:

def process(conn, tasks) do
  items = Map.get(conn.body_params, "items")

  Enum.map(tasks, fn {m, f, a} ->
    apply(m, f, [items | a])
  end)
end

Given a tuple {UserRouterHelpers, :scaling, [10, 42]} this will call UserRouterHelpers.scaling(items, 10, 42).

If you are writing a lot of these, some helper functions could get a result that looks just like what you started with:

# in RouterMFAHelpers
def scaling(vmin, vmax) do
  {WhateverModule, :scaling, [vmin, vmax]}
end

# in the router
import RouterMFAHelpers

tasks=[scaling(0,100),group(1),sum(1),sort(2)] # Many function can be grouped in a list

post "/receive/", private: %{process: tasks} do
  # do something with data
  # then send response
  send_json(conn,  %{status: "success"})
end

Where Next?

Popular in Questions Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New

We're in Beta

About us Mission Statement