How to create a function at compile time, given the name, parameters and functionality, as an input by the user

Is there a way how a user can input data to the program like using the function :

create_function_here (name, params[], string_of_actual_commands){

and then resulting into an actual function with that name, parameters and functionality being created ?

Thanks a lot

yes, there is, but it’s highly recommended to not do it. Your user (intended or not) can cause a memory leak by pushing as many of these as they want. Do you still want to know how to do it?

Yes, please. I am assuming that the user has good intents :slight_smile:

what about users you don’t intend to be on your system? Honestly, there’s probably a better way to do what you’re trying to do. What are you trying to do?

This is going to be a closed system. Only some users can access it.

The code module has some things that might get you where you want to go. It’s a very very bad idea: Do try to find a better way to do what you’re trying to do. But since you want it here is an example:

iex(1)> Code.compile_string("""
...(1)>   defmodule M do
...(1)>     def f(x), do: x + 1
...(1)>   end
...(1)> """)
iex(2)> M.f(2)

Is it possible to be done in actual coding (i.e. inside a module) ?

Why wouldn’t it be? But seriously. Don’t do this.

iex(1)> defmodule Q do
...(1)>   def f(code) do
...(1)>     Code.compile_string(code)
...(1)>   end
...(1)> end
iex(2)> Q.f("""
...(2)>   defmodule M do
...(2)>     def f(x), do: x + 1 
...(2)>   end
...(2)> """)

iex(3)> M.f(2)
1 Like

Like if my employees pushed this code they might be fired. On the spot. Okay, if they were junior, i’d give them a warning. Second time, fired. On the spot.

1 Like

Check out, this solution is safe comparing to compiling Elixir.


Thanks a lot to all who helped.

just to be clear, if you do this in a place where it’s compile time, that’s perfectly fine (and what it’s used for). Not runtime.

@fuelen’s suggestion is excellent.

I will implement this during compile time.

1 Like

if you’re doing it compile time, you may want to consider using macros instead.

1 Like