So I'm still trying to wrap my head around compile-time computing and templates in Nim, but am struggling mightily.
Anyway, I wanted to construct types based on other types (generic types?), but with members of the parameter type as parameters in the type definition. An example that doesn't compile:
type
Dim = object
x, y: int
Thing[Dimension] = object
xs: array[Dimension.x, int]
ys: array[Dimension.y, int]
proc createDim(foo: int): Dim =
result.x = foo + 2
result.y = foo + 3
const someDim = createDim(1)
proc createThing[Dimension](): Thing[Dimension] =
let a = [1, 2, 3]
let b = [1, 2, 3, 4]
result.xs = a
result.ys = b
let someThing = createThing[someDim]()
I want to create the Dimension type at compile time, and then create Thing s based on the members of that type. I have tried with templates, but as I said, I still feel more like randomly adding syntax trying to get it to compile rather than programming a solution. Any pointers would be greatly appreciated.I couldn't figure out how to access members of static variables within a type definition, but found the workaround of writing getters for the fields.
type
Dim = object
x,y:int
#can't seem to access fields of a static object? so declare getters
proc x(d:Dim):int = d.x
proc y(d:Dim):int = d.y
type
Thing[d:static[Dim]] = object
xs: array[d.x,int]
ys: array[d.y,int]
proc initThing(D:static Dim):Thing[D] =
for i in 0..<D.x:
result.xs[i] = i
for i in 0..<D.y:
result.ys[i] = i
const dim_3x4 = Dim[x:3, y: 4]()
let someThing = initThing(dim_3x4)
let otherThing = Thing[Dim(x:4, y: 5)]()
echo someThing #(xs: [0,1,2], ys: [0,1,2,3])
echo otherThing #(xs: [0,0,0,0], ys: [0,0,0,0,0])