gilbertbw
Writing a macro that defines infix operators
I am trying to write a macro to define a custom operator
defmacro infix_function(op, function) do
quote do
def (a unquote(op) b), do: unquote(function)(a, b)
end
end
But I am getting a syntax error on the def (a unquote(op) b) bit. I am not sure if there is an alternative syntax to define operators that would let this work?
As an aside, when pattern matching while writing an operator I am having to do something like this:
def ((%MyStruct{} = a) * b), do: MyStruct.mult(a, b)
Is there an alternative syntax to defining infix operators that is better suited to pattern matching?
Most Liked
NobbZ
There is only a coupld of valid infix operators that you can use.
Plase see Operators reference — Elixir v1.20.2 for more information.
NobbZ
infix_function(:"+", adder/2) could be made work roughly by this, IIRC how things work:
defmodule M do
defmacro infic_function(op, fun)
quote do
def unquote(op)(a, b), do: unqote(fun)(a, b)
end
end
end
You can actually use the same trick for “simpler” pattern matching…
def unquote(:"*")(%MyStruct{} = a, b), do: # impl
Whether or not this is actually “simpler” us left to you…
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
- #forms
- #api
- #metaprogramming
- #security
- #hex









