I'm a student. I am currently doing research about how fast Mojo Lang is. I want to run the recursion code, and compare it to python. I decided to write a simple recursion code, and an error occurred. Please help me.
I tried to make a factorial code. If i run the code, it prints me a factorial of num variable.
here is my code
fn fact(n:Int):
if n==1:
return 1
else:
return n*fact(n-1)
var num = 14
if num<0:
print("sry")
elif num ==0:
print("1")
else:
print(fact(num))
and this is the error
error: Expression [19]:7:16: cannot implicitly convert 'Int' value to 'None' in return value
return 1
^
error: Expression [19]:9:22: ambiguous call to 'fact', each candidate requires 0 implicit conversions, disambiguate with an explicit cast
return n*fact(n-1)
~~~~^~~~~
Expression [19]:5:1: candidate declared here
fn fact(n:Int):
^
Expression [14]:5:1: candidate declared here
def fact(n:Int):
^
error: Expression [19]:29:19: ambiguous call to 'fact', each candidate requires 0 implicit conversions, disambiguate with an explicit cast
print(fact(num))
~~~~^~~~~
Expression [19]:5:1: candidate declared here
fn fact(n:Int):
^
Expression [14]:5:1: candidate declared here
def fact(n:Int):
^
The first error message tells you the problem: the function is meant to return None
and you try to return an Int
. This should hint you how to fix.