verilog
Macros - how are they different to functions? When should they be used? How do they differ to C's macros?
Hello, I’m new to Elixir.
I was reading about the macros of Elixir but didn’t quite get it. I know C and familiar with its marcos.
Although I didn’t quite understand Elixir’s macros yet. Could you answer my basic questions about macros:
- What is the difference between functions and macros in Elixir?
- Why or when Should I use them?
- How they are different for C’s macros?
Most Liked
stefanchrobot
Re 1. Given:
my_thing(:some_param)
If my_thing is a macro, the line above will be evaluated at compilation time, otherwise it will be evaluated at run-time. Note that macro can invoke a function which means the function will be invoked at compilation time, which in turn means you can do all kinds of fancy and crazy stuff at compile-time.
Re 2. Use macros if functions are not enough to remove boilerplate. The line is blurry. Generally, avoid using macros.
Re 3. Elixir macros are safer (hygienic) and more powerful. They transform a piece of Elixir code into a different piece of Elixir code. The coolest thing is that the piece of code you’re working with is expressed as an Elixir data structure.
I highly recommend going through the blog series about macros by Saša Jurić.
NobbZ
C Macros are very similar to the “search and replace” function in your editor, as that is exactly how they are implemented. They are very dumb.
Elixir macros though are able to “understand” the arguments they got and produce completely different code for different arguments.
OvermindDL1
C Macro’s are indeed a templating engine, more similar to EEX than anything else, entirely textual and not AST aware at all. Elixir Macro’s are AST transformers, more like LISP macro’s, which is closer to C++ templates. Essentially an Elixir Macro is a function that executes at compile time to transform one AST form (whatever is passed in to it as an AST instead of as values) and returns a new AST to put in it’s place, and that continues resolving down until it is finally at the ‘base’ AST level and no more expansions can happen, which is then when it is compiled into Erlang.
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
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









