Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mojo-lang error about fn, recursion factorial code

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading