I am trying to parse a file containing half-lives of nuclear isotopes. One of the columns contains the units of the half-life time as a string, and I would like to convert it into Unitful units.
As an example, let’s say I parsed one of the lines and obtained that the unit of half-life is “year”
unit_str = "yr"
Now, I want to convert it to the Unitful units using something along the lines of
using Unitful
hl_unit = @u_str($unit_str)
I thought $unit_str
would interpolate the actual value inside the macro call, however, apparently, it does not work like this.
How can I actually interpolate the value of unit_str
inside the macro call?
What I want in the end is to have
hl_unit = @u_str("yr")
Macros transform code, this is not possible. You sure you should be using @u_str
? There is not a function that does the same thing and can be called over non-literals?
As far as I am aware, there is only a macro version.
Could it be possible to wrap the call to @u_str
inside another macro which does the interpolation?
I have tried to define
macro interpolate_ustr(str)
return :(@u_str($str))
end
Unfortunately, it still does not work…
Macros cannot touch values inside variables in general. They can output code that passes the variable to a function, but they themselves directly only see what a programmer see looking at a code not in execution yet (this is, variable names).
I do not use this library, but it seems to me that @u_str
is useful to automatically import for you some “Units, dimensions, and fundamental constants” but you can manually import them and then call convert?
1 Like
I guess I can directly access the names of the units by constructing the corresponding symbols.
Thank you, @Henrique_Becker.
It is hard to wrap ones head around macroprogramming…
It sure is, My advice is: avoid macro
solutions unless you are entirely sure why you are using a macro
; and keep in mind that macros are “basically” a glorified Regex match and replace/rearrange over code. They just see lines and code and change them to other lines of code.
1 Like