YV17
YV17

Reputation: 389

F# function return value

I'm new to F# and when I was trying to implement function rpt I found some troubles.

let rec rpt f n x =
    if n=0 then x
    else 
       f ( rpt f (n-1) x )

When I have called this function as rpt (fun x -> x*x) 4 2. Answer was ok val it : int = 65536 But when I change rpt as follows (only multiplying by 2) :

let rec rpt f n x =
    if n=0 then 2*x
    else 
       f ( rpt f (n-1) x )

Function returns only zero : val it : int = 0. Can anyone explain what happens?

Upvotes: 2

Views: 747

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80915

Repeating a squaring function four times gives a total power of 2^4 = 16, which perfectly aligns with your first answer - 65536 = 2^16. But if you add an additional second power at the beginning, you get the total power of 16*2 = 32, which happens to be exactly the size of the int type, so it overflows perfectly and gives zero.

You can verify this by replacing int with int64:

let rec rpt f n x =
    if n=0 then 2L*x
    else 
       f ( rpt f (n-1) x )

> rpt (fun x -> x*x) 4 2L;;
val it : int64 = 4294967296L

> pown 2L 32;;
val it : int64 = 4294967296L

Upvotes: 4

Related Questions