#Construct array at comptime

1 messages · Page 1 of 1 (latest)

topaz raven
#

Hello, how can I construct an array in a comptime block but by appending? I don't know the size of the array in advance, so is it possible to make an empty array an iteratively add to it? thanks

#

for instance:

pub const array: [_]usize = comptime blk: {
  //create something i can append to 
  //and at the end pop the array
};
proud blade
#

you can just let the compiler infer the type

#
pub const array = comptime blk: {
  //create something i can append to 
  //and at the end pop the array
};
topaz raven
#

the problem is not the result type, it's inside the comptime, i want to iterate and append

rotund vale
#

so you essentially want a comptime arraylist?

topaz raven
#

i guess, or just a way to do ++= if you see what i mean

rotund vale
#

right

#

i think the issue there is that would change the type

topaz raven
#

yeah, that's my problem

#

it doesn't work with ++

rotund vale
#

could you place an upper bound on the size?

topaz raven
#

i guess!

rotund vale
#

does that solve your issue?

topaz raven
#

ah, well i guess it's more of a workaround than a solution but yes

#

so i understand it's not possible

rotund vale
#

i think you could probably do it with recursion

#

if u write a working version with the workaround ill give that a try

topaz raven
#

thats what i was thinking also, i think i'll try the recursion thing myself!

rotund vale
#

glhf!

livid stone
topaz raven
livid stone
#

This is with loops. IIRC it gets simpler with recursion, because you can use arrays instead of slices

fn makeArray(comptime n: usize) [n]usize {
    var slice: []const usize = &.{};
    for (0..n) |i|
        slice = slice ++ @as([]const usize, &.{i});
    return slice[0..n].*;
}

pub fn main() void {
    const a = comptime makeArray(10);
    @compileLog(a);
}
#

The code could probably be cleaned up a bit, this is only to illustrate the idea.

rotund vale
#

oh what you can just concatenate slices?

livid stone
#

Same as arrays, yes

#

But only at comptime (I think)

rotund vale
#

has to be comptime only yeah

topaz raven
#

nice, thanks !

#

awesome

#

that's what i was looking for