1
votes
let rec prime : int -> bool
 = fun n -> let rec f a = if (a = 1) then 1 
                       else if (n mod a) = 0 then 0 
                       else if ((f a-1) = 1) then 1 
                       else 0 
                       in 
                       if ((f n-1) = 1) then true 
                       else false 

As you can see from my code, I want to implement a function which can tell given number is prime or not.

I can compile and run this code, but for all X function tell "false".

Why this happens?

Thanks in advance. :)

2
I recommend to always add white spaces around binary operators. You get less confused by writing f n - 1 than f n-1 which many beginners misread as f (n-1). - camlspotter

2 Answers

0
votes

The expression:

f n-1

is parsed like this:

(f n) - 1

You need to write this:

f (n - 1)
0
votes
((f n-1) = 1)

f n-1 is equivalent to (f n) - 1, not f (n - 1). So you're taking a number that's either 0 or 1, then subtract 1 from (yielding either -1 or 0) and then seeing whether it's 1, which it can never be.

Note that this wouldn't even have compiled had you made f return a boolean rather than an integer (you can't subtract from a boolean).