I typically write a few simple programs in any new language. I mostly write the standard ones: factorial, a guessing game, fibonacci numbers, etc.
Here I have my F# code for Fibonacci numbers. I also write (when it’s applicable) an arbitrary precision version, to print out integers larger than those that can be stored in a regular integer type.
#light
let fib n =
let rec fib_aux (n, a, b) =
match (n, a, b) with
| (0, a, b) -> a
| _ -> fib_aux (n - 1, a + b, a)
fib_aux (n, 0, 1)
This Fibonacci code is properly tail recursive, and uses a helper function.
However, it will overflow and return negative numbers after a certain point.
> fib 20;;
val it : int = 6765
> fib 200;;
val it : int = -552082539
We can get arbitrary precision using BigInts. In F#, this is done very easily (we don’t even have to open Math.BigInt!).
let big_fib n =
let rec big_fib_aux (n, a, b) =
match (n, a, b) with
| (0, a, b) -> a
| _ -> big_fib_aux (n - 1, a + b, a)
big_fib_aux (n, 0I, 1I)
Notice how all we need to do is use the “I” literal in the tail call for the numbers in the tuple.
> big_fib 20;;
val it : bigint = 6765I
> big_fib 200;;
val it : bigint = 280571172992510140037611932413038677189525I