A way to mixin during runtime?

Steven Schveighoffer schveiguy at gmail.com
Fri Aug 27 13:44:04 UTC 2021


On 8/27/21 6:34 AM, Kirill wrote:
> On Friday, 27 August 2021 at 09:51:46 UTC, Mathias LANG wrote:
>> On Friday, 27 August 2021 at 06:52:10 UTC, Kirill wrote:
>>> Is there a way to do mixin or similar during runtime?
>>>
>>> I'm trying to read a csv file and extract data types. Any ideas on 
>>> how this should be approached in D are greatly appreciated.
>>
>> You cannot mixin at runtime. However, it is fairly easy to map a 
>> finite and CT-know set of argument to runtime arguments via `static 
>> foreach`.
>> Could you give us example of the content of your CSV file and what you 
>> are trying to do ?
> 
> Each csv file will be different.
> 
> For example:
> ```
> name;surname;age;grade
> Alex;Wong;18;87
> John;Doe;19;65
> Alice;Doe;18;73
> etc...
> ```
> 
> I'd like to extract the data types automatically. For instance, if using 
> tuples:
> ```
> Tuple!(string, string, int, int) ...
> ```
> instead I'd like to have:
> ```
> auto mytuple = read_csv(path); // returns Tuple!(string, string, int, 
> int)[]
> ```

So you can't build "new types" at runtime that are usable after your 
code is compiled. But there are options:

1. You can parse the CSV at compile-time using `import("types.csv");` 
and then processing the resulting string using CTFE (not sure if std.csv 
does this, but I'd expect it to). Then you can use the resulting thing 
to generate string mixins that can generate types. This has the drawback 
that you need to recompile when your csv input changes.

2. You can create a dynamic type that deals with the CSV data. It looks 
from your CSV data you are inferring the "type" from the data itself, 
which is complex in itself. In this case, you'd use it kind of like a 
JSON object, where you index the fields by name instead of using 
`obj.name`, and you'd have to extract the type dynamically from the type 
inference you'd have to write. This is pretty much what std.csv does, 
though you can dress it up a bit more.

Without the CSV telling you types, it's hard to make something "easy". I 
have written code that extracts from JSON data and database data 
serializable struct types, and builds a D file, but it's never 
clean-cut, and sometimes you have to hand-edit that stuff. This is about 
as "easy" as it gets, just have the computer do most of the heavy 
lifting, and then massage it into something usable.

-Steve


More information about the Digitalmars-d-learn mailing list