CharlesIrvine
Convert boolean expression into an anonymous function
I’m wondering if the following is possible:
I have an application where I would like to parse boolean expressions and produce corresponding anonymous functions. These expressions:
x > y
x == y
x == y + 3
would be converted to:
fn data -> data.x > data.y
fn data -> data.x == data.y
fn data -> data.x == data.y + 3
Possible?
Most Liked
benwilson512
Hey @CharlesIrvine can you elaborate if you are being passed these expressions as strings from users or other untrusted sources at runtime, vs compile time expressions?
Last Post!
al2o3cr
There are useful shorthands like quote, but ultimately macros are transformations from AST to AST. For your example:
# INPUT
iex(1)> quote do: x > y
{
:>,
[context: Elixir, import: Kernel],
[
{:x, [if_undefined: :apply], Elixir},
{:y, [if_undefined: :apply], Elixir}
]
}
# OUTPUT
iex(2)> quote do: data.x > data.y
{
:>,
[context: Elixir, import: Kernel],
[
{
{
:.,
[],
[
{:data, [if_undefined: :apply], Elixir},
:x
]
},
[no_parens: true],
[]
},
{
{
:.,
[],
[
{:data, [if_undefined: :apply], Elixir},
:y
]
},
[no_parens: true],
[]
}
]
}
The underlying pattern looks like:
{:some_var, _, _} -> {{:., [], {:data, [], Elixir}, :some_var}
You’d apply a transformation like this using a function like Macro.prewalk or your own recursive traversal code.
Once you’ve got the data-fied expression, you’d wrap it in the AST corresponding to fn data -> ... end. You can find that shape using quote:
iex(4)> quote do: fn data -> :ok end
{:fn, [], [{:->, [], [[{:data, [if_undefined: :apply], Elixir}], :ok]}]}
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









