I am new to Elixir and I can’t manage to wrap my head around it and find a solution. Basically I have a struct made out of strings and I have a method which replaces placeholders within the struct values by using a tuple, an example of a string value would be: “Hello ${name}!” with the tuple {“name”, “world”} would print out: Hello world!. That’s basically how it should work (just to set the idea).
Now I managed to make my code work and replace the placeholders, but I hardcoded it, so only specific placeholders can be replaced. I used regex to find all placeholders and list them so it’s not a problem to dynamically find them.
Here comes the problem:
I need to call a method for every placeholder there is and get the updated value and call it again on it until all of the placeholders are called and get the end result of the struct. The following code made sense in my head initially because of my previous knowledge of C type languages:
struct = # do some methods to get the initial value
Enum.each placeholders, fn({placeholder, data}) ->
struct = StructModule.replace(struct, placeholder, data)
end
I mean I guess you could see the general idea which I have here. But, again, as Elixir is an immutable language I do get the data variable on the left hand side of the equation sign but on the next call it is forgotten. I guess it can’t reassign the value of the scope one level above?
It’d be a great help if anyone could link me somewhere where I could find a solution!
If I am getting the problem right, I think the best way to solve it would be to use a reducer. The problem is that with each call, you reassign what is in struct, but the code actually uses the initial struct instead of the one computed on the previous call.
So I believe it could be something similar to:
initial_struct = # do some methods to get the initial value
Enum.reduce placeholders, initial_struct, fn({placeholder, data}, acc) ->
StructModule.replace(acc, placeholder, data)
end