M
Modular15mo ago
Larsis

How to use Modulo?

This works print(10%) but I can't use % in a method:
def is_prime(n):
for i in range(2,n):
if (n%i) == 0:
return False
return True
def is_prime(n):
for i in range(2,n):
if (n%i) == 0:
return False
return True
How come I get the following error?
error: Expression [8]:7:10: 'object' does not implement the '__mod__' method
if (n%i) == 0:
~^

expression failed to parse (no further compiler diagnostics)
error: Expression [8]:7:10: 'object' does not implement the '__mod__' method
if (n%i) == 0:
~^

expression failed to parse (no further compiler diagnostics)
5 Replies
alvinjrush
alvinjrush15mo ago
I declared the n's type in is_prime's arguments and it worked perfectly well.
alvinjrush
alvinjrush15mo ago
No description
Moosems / Three chickens
Since you didn’t give an explicit type it assumes object but since that entails things like String understandably it would be worried. Declare it as a number like Int and it works as Alvin showed.
guidorice
guidorice15mo ago
Oof, this is a tough one. What if n is based on a parameter, not an argument? I cannot think of a workaround. I tried using math.mod but kind of went down a rabbit hole of type casting .
PriNova
PriNova15mo ago
If the parameter is an object and you want a modulo, this is a workaround:
fn intMod[o: object](mod: Int) -> Int:
if o._value.is_int():
return (o._value.get_as_int() % mod).to_int()
return -1
fn intMod[o: object](mod: Int) -> Int:
if o._value.is_int():
return (o._value.get_as_int() % mod).to_int()
return -1
Called with:
fn main():
alias o = object(10)
let result = intMod[o](4)
fn main():
alias o = object(10)
let result = intMod[o](4)
Important here, the object must be an alias, because dynamic types are not supported. Mojo encourages by using SIMD types, which is preferred for parallel execution and tiling etc. These are the primitives to use efficiently. SIMD also has a __mod__ dunder for calculating the modulo.
Want results from more Discord servers?
Add your server