Skip to content

Instantly share code, notes, and snippets.

@celsojr
Last active November 19, 2023 11:37
Show Gist options
  • Save celsojr/7a7ff7fc1db5ea3c16f3a720f8cbcc2c to your computer and use it in GitHub Desktop.
Save celsojr/7a7ff7fc1db5ea3c16f3a720f8cbcc2c to your computer and use it in GitHub Desktop.
F# Tail Recursive Factorial in a functional programming approach
(*--------------------------------------------------------------------------------------------
* Copyright (c) 2017 Celso Junior, [email protected]. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* F# Tail Recursive Factorial in a functional programming approach.
* Also using the CPS technique (Continuation Passing Style).
* Ref.: https://en.wikipedia.org/wiki/Continuation-passing_style
* --------------------------------------------------------------------------------------------*)
[<TailCall>]
let fac1 x =
let rec fac2 x f =
match x with
| 0u | 1u -> f()
| _ -> fac2 (x - 1u) (fun () -> x * f())
fac2 x (fun () -> 1u)
[0u..10u] |> List.iter (fun i -> printfn "%02d! = %d" i (fac1 i))
(* the output
00! = 1
01! = 1
02! = 2
03! = 6
04! = 24
05! = 120
06! = 720
07! = 5040
08! = 40320
09! = 362880
10! = 3628800
*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment