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 ?
Trending in Questions
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixirconf-us
- #ai
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 3- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
al2o3cr
quotereturns 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
plugand 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. Yourprocessfunction might be written as:Given a tuple
{UserRouterHelpers, :scaling, [10, 42]}this will callUserRouterHelpers.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:
LionelMarco
Thanks. apply(MFA) is pretty similar to C language function pointers.
I resolve
kernel.apply( __ MODULE __,f,arg) give me the anonymous function then evaluate it with dot(value)
Greetings
krasenyp
On an almost unrelated note, you can replace the
conds with clauses. More info here.