0

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):
^

2 Answers 2

1

According the documentation of fn:

a missing return type specifier is interpreted as returning None instead of an unknown return type.

So you should specify the return type for the fact function as Int, because the interpreter assumes None and complains when the function return an Int.

fn fact(n:Int) -> Int:
    if n==1:
        return 1
    else:
        return n*fact(n-1)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.