ocaml-programming

Simple OCaml programs
git clone git://git.laack.co/ocaml-programming.git
Log | Files | Refs | README

commit 02f19810d65aef58bbf54f1fc629d22d354e62de
parent 559120bedfb894798fbd06be8f7958824dbf1ed3
Author: Andrew Laack <andrew@laack.co>
Date:   Mon, 17 Aug 2026 18:26:48 -0500

Did a few more exercises, played with dune

Diffstat:
A.gitignore | 1+
Ach1_self_learning/dune | 3+++
Ach1_self_learning/dune-project | 1+
Ach1_self_learning/newton_sqrt.ml | 17+++++++++++++++++
Ach2/slow_factorial.ml | 5+++++
Ach2/tail_factorial.ml | 15+++++++++++++++
6 files changed, 42 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1 @@ +_build/ diff --git a/ch1_self_learning/dune b/ch1_self_learning/dune @@ -0,0 +1,3 @@ +(executable + (name newton_sqrt) + (libraries qcheck)) diff --git a/ch1_self_learning/dune-project b/ch1_self_learning/dune-project @@ -0,0 +1 @@ +(lang dune 3.0) diff --git a/ch1_self_learning/newton_sqrt.ml b/ch1_self_learning/newton_sqrt.ml @@ -0,0 +1,16 @@ +let abs_diff x y = abs_float (x -. y);; + +let newton_sqrt x = + let rec go guess = + let diff = abs_diff x (guess *. guess) in + if diff < 0.0000000001 + then guess + else go ((guess +. x /. guess) /. 2.) + in go x;; + + +let reverse = QCheck.Test.make + (QCheck.float_range 0. 100000.) + (fun n -> (abs_diff n ((newton_sqrt n) *. (newton_sqrt n))) < 0.00001);; + +QCheck_base_runner.run_tests [ reverse ];;+ \ No newline at end of file diff --git a/ch2/slow_factorial.ml b/ch2/slow_factorial.ml @@ -0,0 +1,5 @@ +let rec factorial n = + if n = 0 then 1 + else n * factorial (n - 1);; + +print_endline (string_of_int (factorial 10));; diff --git a/ch2/tail_factorial.ml b/ch2/tail_factorial.ml @@ -0,0 +1,15 @@ +let factorial x = + let rec go acc current = + if current = 0 + then acc + else + go (acc * current) (current - 1) + in go 1 x;; + + +print_endline (string_of_int(factorial 1));; +print_endline (string_of_int(factorial 2));; +print_endline (string_of_int(factorial 3));; +print_endline (string_of_int(factorial 4));; +print_endline (string_of_int(factorial 5));; +print_endline (string_of_int(factorial 6));;