M
Modular13mo ago
JIMC

Compile time addition of numbers

I am trying to do compile time addition of numbers via generic types, e.g.
from memory import stack_allocation

struct IntType[num: Int]:
alias value: Int = num

fn comptime_add[Num1: IntType[num1: Int], Num2: IntType[num2: Int]]() -> IntType[num1 + num2]:
return Num1.value + Num2.value
from memory import stack_allocation

struct IntType[num: Int]:
alias value: Int = num

fn comptime_add[Num1: IntType[num1: Int], Num2: IntType[num2: Int]]() -> IntType[num1 + num2]:
return Num1.value + Num2.value
The errors are:
array2.mojo:6:31: error: use of unknown declaration 'num1'
fn comptime_add[Num1: IntType[num1: Int], Num2: IntType[num2: Int]]() -> IntType[num1 + num2]:
^~~~
array2.mojo:6:57: error: use of unknown declaration 'num2'
fn comptime_add[Num1: IntType[num1: Int], Num2: IntType[num2: Int]]() -> IntType[num1 + num2]:
^~~~
array2.mojo:6:82: error: use of unknown declaration 'num1'
fn comptime_add[Num1: IntType[num1: Int], Num2: IntType[num2: Int]]() -> IntType[num1 + num2]:
^~~~
array2.mojo:6:89: error: use of unknown declaration 'num2'
fn comptime_add[Num1: IntType[num1: Int], Num2: IntType[num2: Int]]() -> IntType[num1 + num2]:
array2.mojo:6:31: error: use of unknown declaration 'num1'
fn comptime_add[Num1: IntType[num1: Int], Num2: IntType[num2: Int]]() -> IntType[num1 + num2]:
^~~~
array2.mojo:6:57: error: use of unknown declaration 'num2'
fn comptime_add[Num1: IntType[num1: Int], Num2: IntType[num2: Int]]() -> IntType[num1 + num2]:
^~~~
array2.mojo:6:82: error: use of unknown declaration 'num1'
fn comptime_add[Num1: IntType[num1: Int], Num2: IntType[num2: Int]]() -> IntType[num1 + num2]:
^~~~
array2.mojo:6:89: error: use of unknown declaration 'num2'
fn comptime_add[Num1: IntType[num1: Int], Num2: IntType[num2: Int]]() -> IntType[num1 + num2]:
How should I approach this?
1 Reply
Stole
Stole13mo ago
You can directly use Int, no need for IntType
fn comptime_add[Num1: Int, Num2: Int]() -> Int:
return Num1 + Num2

fn main():
alias N = comptime_add[1, 2]()
print(N)
fn comptime_add[Num1: Int, Num2: Int]() -> Int:
return Num1 + Num2

fn main():
alias N = comptime_add[1, 2]()
print(N)
This prints 3 as expected
Want results from more Discord servers?
Add your server