LionelMarco

LionelMarco

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 ?

Showing Posts 1 to 3

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
LionelMarco

LionelMarco OP

Thanks. apply(MFA) is pretty similar to C language function pointers.

I resolve


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

 end



def do_task(items) do
  fn {f,arg} ->
    IO.inspect(f, label: "f")
    IO.inspect(arg, label: "arg")
    Enum.map(items,fn value -> apply( __MODULE__,f,arg).(value) end)
  end
end

kernel.apply( __ MODULE __,f,arg) give me the anonymous function then evaluate it with dot(value)

Greetings

krasenyp

krasenyp

On an almost unrelated note, you can replace the conds with clauses. More info here.

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews