0

I am trying to write a code which checks if number is Fibonacci or not in ML. I am a beginner. Help me find out what is the problem with my code.

fun isfib(n :int): bool=
let
  val a1=1;
  val a2=1;
  val temp=0;
in
  while a2<n do (
    a1=temp
    a2=a1
    a2=temp+a2
  )
  if a2=n then true
  else false
end;
sepp2k
  • 363,768
  • 54
  • 674
  • 675
Asav Patel
  • 1,113
  • 1
  • 7
  • 25

1 Answers1

0
a1=temp
a2=a1
a2=temp+a2

= is the equality operator in SML, not an assignment operator. So the above code is just equivalent to this:

false (* because a1 is 1, but temp is 0 *)
true (* because a1 and a2 are both 1 *)
true (* because 1 = 0 + 1 *)

So you have three side-effect-free expressions in your loop, so it just won't do anything.

It's clear that you actually want to change the values of those variables, but you can't do that. Variables in SML are immutable - you can't change them after they're set. So even having a while condition like a2 < n doesn't make sense because a2 and n can't change, so the condition is either always true or always false. If you want to use a while loop like this, you should look into the ref type, which allows you to create mutable values that you can use to simulate mutable variables.

That said using while loops and mutation is not idiomatic SML. There's a reason why variables in SML aren't mutable: the language designers want to encourage you to not rely on mutation (and thus also not on while loops). The idiomatic way to loop in SML is to either use higher order functions (like map, filter, foldl etc.) or recursion. For your problem a recursive function would make the most sense.

sepp2k
  • 363,768
  • 54
  • 674
  • 675