Search code examples
smlnjml

Check Whether or Not An Input is a Fibonacci Number


fun isfib(a) =
   findfib(a,1,1)

and
findfib(b,x,y) =
   val z = x + y
   if b <= 1 then true
   else if z > b then false
   else if z = b then true
   else fib(b,y,z)

I'm placing an input into the program and recursively trying to find out if this input is a fib number or not. I can calculate the xth place of fib in a separate program in 2 lines. But this "input, check if equals fib, do fib to infinity or bust" logic is extremely confusing to me. I'm also getting errors such as "replacing AND with ANDALSO" and "inserting ORELSE" on line 7.1 which is B<=1


Solution

  • I mean that you should use and for cases where you need mutual recursion, in this case it doesn't seems like you really do, for example, you could try something like this:

    fun fib 0 = 1
        | fib 1 = 1
        | fib n = (fib (n-1)) + (fib (n-2));
    
    fun isfib a = 
        let
            fun eval a b = if a = (fib b) then true else if a < (fib b) then false else eval a (b+1)
        in
            eval a (1)
    end;
    

    Try running isfib 5 and isfib 6 for example. No infinity required.