Compile time addition of numbers
I am trying to do compile time addition of numbers via generic types, e.g.
The errors are:
How should I approach this?
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
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]:
1 Reply
You can directly use
This prints 3 as expected
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)