Sunday, September 14, 2025

OCAML READING AND WRITING TO A FILE

 


REVISED: Sunday, September 14, 2025




1. OCAML  READING AND WRITING TO A FILE

(*
This script performs several file and number operations:

1. It prompts the user to enter integers, writing them to a file named "integers.txt".
 It handles file creation and appending automatically.

2. It reads the "integers.txt" file.

3. It identifies any prime numbers from the list of integers.  A prime number is a natural number, a counting number, greater than 1 with no positive divisors or factors other than 1 and itself.

4. It writes the identified prime numbers to a file named "primes.txt".

 5. Finally, it displays the full content of both "integers.txt" and "primes.txt".
*)

(*
 ==================================================================
  PART 1: WRITE INTEGERS TO A FILE
 ==================================================================
  This section handles capturing user input and writing it to 'integers.txt'.
*)

(*
  The 'write_integers' function opens 'integers.txt' and recursively prompts
  the user for input until they type 'exit'.
*)
let write_integers () =
  (*
    'Out_channel.open_gen' is used to open a file for writing.
    - '[Open_append; Open_creat]' is a list of flags:
      - 'Open_append': If the file exists, new content will be added to the end.
      - 'Open_creat': If the file does not exist, it will be created.
    - '0o666' sets the file permissions (read and write for owner, group, and others).
    - '"integers.txt"' is the name of the file to open.
    This combination elegantly handles both cases of the file existing or not.
  *)
  let oc = Out_channel.open_gen [Open_append; Open_creat] 0o666 "integers.txt" in
  (*
    A recursive function 'loop' is defined to continuously ask for user input.
    This is a common pattern in functional programming for creating loops.
  *)
  let rec loop () =
    print_string "Enter an integer (or 'exit' to finish): ";
    (* 'flush stdout' ensures the prompt is immediately visible to the user. *)
    flush stdout;
    (* 'read_line ()' captures a line of text from the user's input. *)
    let input = read_line () in
    (* We check if the user's input is the word "exit". *)
    if input <> "exit" then
      (*
        A 'try-with' block is used for error handling. It attempts to convert
        the user's input string into an integer.
      *)
      try
        (* 'int_of_string' attempts the conversion. *)
        let num = int_of_string input in
        (*
          If successful, 'fprintf' writes the formatted string to the output channel 'oc'.
          - '%d\n' is a format specifier: '%d' for an integer, '\n' for a new line.
          This ensures each number is on its own line in the file.
        *)
        Printf.fprintf oc "%d\n" num;
        (* The 'loop' function calls itself to ask for the next input. *)
        loop ()
      with
      (*
        If 'int_of_string' fails (e.g., input is "abc"), it raises a 'Failure' exception.
        The 'with' block catches this exception.
      *)
      | Failure _ ->
        (* An error message is printed to the console. *)
        print_endline "Invalid input. Please enter an integer.";
        (* The loop continues, asking for input again. *)
        loop ()
  in
  (* The initial call to the recursive loop function to start the process. *)
  loop ();
  (*
    It's crucial to close the output channel to ensure all data is written to the
    file and to free up system resources.
  *)
  Out_channel.close oc;
  print_endline "\nIntegers have been saved to integers.txt.\n"
;;

(*
 ==================================================================
  PART 2: READ INTEGERS, FIND PRIMES, AND WRITE TO A NEW FILE
 ==================================================================
  This section reads the created 'integers.txt' file, processes the numbers
  to find primes, and writes them to 'primes.txt'.
*)

(*
  The 'is_prime' function checks if a given integer is a prime number.
  - 'n': The integer to check.
  - Returns 'true' if prime, 'false' otherwise.
*)
let is_prime n =
  (* Prime numbers must be greater than 1. *)
  if n <= 1 then false
  else
    (*
      A recursive helper function 'is_not_divisible_from' checks for factors.
      - 'd': The current divisor to test.
    *)
    let rec is_not_divisible_from d =
      (*
        The base case for the recursion. If the divisor squared is greater than 'n',
        it means we have checked all possible factors up to the square root of 'n'.
        If no factors were found, the number is prime.
      *)
      if d * d > n then true
      (*
        'n mod d = 0' checks if 'd' is a factor of 'n' (i.e., division has no remainder).
        If it is, 'n' is not prime.
      *)
      else if n mod d = 0 then false
      (*
        If 'd' is not a factor, we recursively call the function with the next
        divisor, 'd + 1'.
      *)
      else is_not_divisible_from (d + 1)
    in
    (* The check for factors starts from 2. *)
    is_not_divisible_from 2
;;

(*
  This function reads integers from the input file, identifies the primes,
  and writes them to the output file.
*)
let process_primes () =
  (*
    A 'try-with' block to handle the case where 'integers.txt' might not exist,
    although our script always creates it. This is good practice for file I/O.
  *)
  try
    (* Open the input file 'integers.txt' for reading. *)
    let ic = In_channel.open_text "integers.txt" in
    (*
      Open the output file 'primes.txt' for writing, using the same append/create
      strategy as in Part 1.
    *)
    let oc = Out_channel.open_gen [Open_append; Open_creat] 0o666 "primes.txt" in
    (*
      A recursive function to read each line from the input channel. It uses
      pattern matching on the 'string option' returned by 'input_line'.
    *)
    let rec read_loop () =
      match In_channel.input_line ic with
      | Some line ->
        (* A 'try-with' handles cases where a line is not a valid integer. *)
        (try
          (* The string from the file is converted back to an integer. *)
          let num = int_of_string line in
          (* The 'is_prime' function is called to test the number. *)
          if is_prime num then
            (* If it's a prime, it's written to the 'primes.txt' file. *)
            Printf.fprintf oc "%d\n" num
        with Failure _ -> ()); (* If conversion fails, ignore the line *)
        (* The loop continues to the next line. *)
        read_loop ()
      (* 'None' indicates the end of the file. *)
      | None -> () (* Stop the loop. *)
    in
    (* Start the reading loop. *)
    read_loop ();
    (* Close both the input and output file channels. *)
    In_channel.close ic;
    Out_channel.close oc;
    print_endline "Prime numbers have been processed and saved to primes.txt.\n"
  with
  (* If 'integers.txt' cannot be opened, this error is caught. *)
  | Sys_error msg -> Printf.eprintf "Error processing files: %s\n" msg
;;

(*
 ==================================================================
  PART 3: DISPLAY THE CONTENTS OF BOTH FILES
  ==================================================================
  This section reads and prints the final contents of both files to the console.
*)

(*
  A reusable helper function to read and print the entire content of a given file.
  - 'filename': The name of the file to read.
*)
let print_file_contents filename =
  (* A descriptive header is printed. *)
  print_endline ("---- Contents of " ^ filename ^ " ----");
  try
    (* Open the specified file for reading. *)
    let ic = In_channel.open_text filename in
    (*
      A recursive function to read and print each line until the end of the
      file is reached.
    *)
    let rec print_lines () =
       match In_channel.input_line ic with
       | Some line ->
         print_endline line;
         print_lines ()
       | None -> () (* End of file, stop recursion. *)
    in
    print_lines ();
    (* When the recursion is done, close the file. *)
    In_channel.close ic
  with Sys_error _ ->
    (* If the file doesn't exist, print a message indicating that. *)
    print_endline "(File is empty or does not exist)";
  (* Print a blank line for better formatting. *)
  print_endline ""
;;

(*
 ==================================================================
  MAIN EXECUTION BLOCK
 ==================================================================
  This is the main part of the script that calls the functions in order.
*)

(*
  The 'let () =' syntax is used for running side-effecting code at the top level.
  It defines a unit value, effectively just running the code on the right.
*)
let () =
  (* 1. Call the function to get user input and write to 'integers.txt'. *)
 s  write_integer();
  (* 2. Call the function to read 'integers.txt' and write primes to 'primes.txt'. *)
  process_primes ();
  (* 3. Print the complete contents of the 'integers.txt' file. *)
  print_file_contents "integers.txt";
  (* 4. Print the complete contents of the 'primes.txt' file. *)
  print_file_contents "primes.txt"
;;

2. CONCLUSION

OCaml version: The OCaml toplevel, version 5.3.0
Coq-LSP version: 0.2.3
PS C:\AI2025> & C:/Users/User/OneDrive/Documents/DOCUMENTS/AI2025/.venv/Scripts/Activate.ps1
(.venv) PS C:\AI2025>  ocaml C:\AI2025\number_operations.ml
Enter an integer (or 'exit' to finish): 1
Enter an integer (or 'exit' to finish): 2
Enter an integer (or 'exit' to finish): 3
Enter an integer (or 'exit' to finish): 4
Enter an integer (or 'exit' to finish): 5
Enter an integer (or 'exit' to finish): 
Invalid input. Please enter an integer.
Enter an integer (or 'exit' to finish): 6
Enter an integer (or 'exit' to finish): 7
Enter an integer (or 'exit' to finish): 8
Enter an integer (or 'exit' to finish): 9
Enter an integer (or 'exit' to finish): exit

Integers have been saved to integers.txt.

Prime numbers have been processed and saved to primes.txt.

---- Contents of integers.txt ----
1
2
3
4
5
6
7
8
9
---- Contents of primes.txt ----
2
3
5
7
(.venv) PS C:\AI2025> 

3. REFERENCES

Bird, R. (2015). Thinking Functionally with Haskell. Cambridge, England: Cambridge University Press.

Davie, A. (1992). Introduction to Functional Programming Systems Using Haskell. Cambridge, England: Cambridge University Press.

Goerzen, J. & O'Sullivan, B. &  Stewart, D. (2008). Real World Haskell. Sebastopol, CA: O'Reilly Media, Inc.

Hutton, G. (2007). Programming in Haskell. New York: Cambridge University Press.

Lipovača, M. (2011). Learn You a Haskell for Great Good!: A Beginner's Guide. San Francisco, CA: No Starch Press, Inc.

Pierce, Benjamin C., et al., editors. Logical Foundations. Vol. 1 of Software Foundations. Electronic Textbook, 2024. Version 6.7, http://softwarefoundations.cis.upenn.edu.

Thompson, S. (2011). The Craft of Functional Programming. Edinburgh Gate, Harlow, England: Pearson Education Limited.

OCAML LIST COMPREHENSION

 

REVISED: Sunday, September 14, 2025




1. OCAML  LIST COMPREHENSION

(*
START
filter_list.ml

Here is an OCaml script that filters a list based on a condition and prints the result, effectively satisfying the list comprehension [ x | x <- [0..9], x <= 5 ].

The script uses the standard library function List.filter, which is the idiomatic OCaml way to perform this kind of operation.
*)

(*
OCaml script to emulate the list comprehension:
[ x | x <- [0,1,2,3,4,5,6,7,8,9], x <= 5 ]
*)

(*
1. Define the initial list of numbers. 
*)

let numbers = [0; 1; 2; 3; 4; 5; 6; 7; 8; 9]

(*
2. Use List.filter to create the new list.
List.filter takes a predicate function (a function that returns true or false)
and a list. It returns a new list containing only the elements
for which the predicate returns true. Here, our predicate is `fun x -> x <= 5`.
*)

let filtered_list = List.filter (fun x -> x <= 5) numbers

(*
3. To print the list in a readable format, we first convert each integer to a string and then join them together with a separator.
*)

let () =
  print_string "[";
  print_string (String.concat "; " (List.map string_of_int filtered_list));
  print_string "]\n"

(*
Power Shell (PS)
You can run it directly with the OCaml interpreter.

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindows

OCaml version: The OCaml toplevel, version 5.3.0
Coq-LSP version: 0.2.3
Loading personal and system profiles took 1074ms.
PS C:\Users\User> ocaml C:\AI2025\filter_list.ml
[0; 1; 2; 3; 4; 5]
PS C:\Users\User>
*)

(*
END
filter_list.ml
*)

2. CONCLUSION

Above is an OCaml script that filters the list  [0; 1; 2; 3; 4; 5; 6; 7; 8; 9]  based on the condition  x <= 5,  and prints the result [0; 1; 2; 3; 4; 5], effectively satisfying the list comprehension [ x | x <- [0..9], x <= 5 ].

3. REFERENCES

Bird, R. (2015). Thinking Functionally with Haskell. Cambridge, England: Cambridge University Press.

Davie, A. (1992). Introduction to Functional Programming Systems Using Haskell. Cambridge, England: Cambridge University Press.

Goerzen, J. & O'Sullivan, B. &  Stewart, D. (2008). Real World Haskell. Sebastopol, CA: O'Reilly Media, Inc.

Hutton, G. (2007). Programming in Haskell. New York: Cambridge University Press.

Lipovača, M. (2011). Learn You a Haskell for Great Good!: A Beginner's Guide. San Francisco, CA: No Starch Press, Inc.

Pierce, Benjamin C., et al., editors. Logical Foundations. Vol. 1 of Software Foundations. Electronic Textbook, 2024. Version 6.7, http://softwarefoundations.cis.upenn.edu.

Thompson, S. (2011). The Craft of Functional Programming. Edinburgh Gate, Harlow, England: Pearson Education Limited.

Friday, September 12, 2025

OCAML FUNCTIONS

 

 REVISED: Sunday, September 14, 2025




1. OCAML  FUNCTIONS

The OCaml Fibonacci Sequence script shown in  the previous tutorial  is logically divided into three main functions and an entry point.

A. let rec fib n = ...
This is the core computational function of the script. Its purpose is to calculate the Fibonacci number for a given integer index n.

let rec fib n: This declares a function named fib that takes a single argument, n. The rec keyword is crucial; it signifies that this is a recursive function, meaning it is allowed to call itself within its own definition.

match n with: This is OCaml's powerful pattern-matching construct. It inspects the value of n and executes the code corresponding to the first pattern it matches.

| 0 -> 0: This is the first "base case" of the recursion. If n is 0, the function immediately returns 0.

| 1 -> 1: This is the second base case. If n is 1, it returns 1. These base cases are essential to prevent the function from calling itself infinitely.

| _ -> fib (n - 1) + fib (n - 2): This is the "recursive step". The underscore _ is a wildcard that matches any value not caught by the preceding patterns (i.e., any integer greater than 1). In this case, the function calls itself twice: once with n - 1 and once with n - 2, and returns the sum of their results. This perfectly models the definition of the Fibonacci sequence.

B. let print_fib_sequence start_num end_num = ...
This function handles the logic for displaying a segment of the Fibonacci sequence to the user.

let print_fib_sequence start_num end_num: This defines a function that takes two arguments, start_num and end_num, which represent the desired range.

Input Validation: The first two if/else if statements act as guards. They check for invalid user input, such as negative numbers or a starting number that is larger than the ending number, and print an appropriate error message if found.

for i = start_num to end_num do ... done: If the input is valid, the function uses a standard for loop. This is an imperative-style feature in OCaml used here for its simplicity in iterating through a range of numbers. The loop variable i will take on every integer value from start_num to end_num, inclusive.

let result = fib i in: Inside the loop, for each number i, it calls the fib function we just discussed to get the corresponding Fibonacci number and stores it in a variable called result.

print_endline ("Fib...": This line constructs the output string. It uses the string_of_int function to convert the integers i and result into strings, and the ^ operator to concatenate them into a user-friendly format (e.g., "Fib(5) = 5"). Finally, print_endline prints this string to the console, automatically adding a newline at the end.

C. let rec main_loop () = ...
This function creates the interactive command-line interface that the user interacts with. It's a recursive loop that keeps running until the user decides to exit.

let rec main_loop (): This defines a recursive function that takes () (called "unit") as an argument. Unit is a special type in OCaml that indicates the absence of a meaningful value, which is common for functions that exist primarily for their side effects, like printing to or reading from the console.

Prompting the User: print_string displays the prompt, and flush stdout ensures that the prompt is immediately visible on the screen rather than being held in an output buffer.

Reading Input: let input = read_line () in pauses the program and waits for the user to type a line of text and press Enter. The entered text is stored in the input variable.

match input with: Pattern matching is used again to decide what to do with the user's input.

| "exit" -> print_endline "Goodbye!": This is the base case for this recursive loop. If the user types exactly "exit", a goodbye message is printed, and the function simply finishes without calling itself again. This breaks the chain of recursive calls and ends the program.

| _ -> ...: If the input is anything else, this block is executed.

Error Handling (try...with): Because parsing user input can fail (e.g., if they type "hello"), the parsing logic is wrapped in a try...with block.

Scanf.sscanf input "%d %d" print_fib_sequence: This is the "happy path". Scanf.sscanf is a versatile function that attempts to parse the input string according to a format string. Here, "%d %d" tells it to look for two integers separated by a space. If it successfully finds them, it passes those two integers directly as arguments to the print_fib_sequence function, which then runs.

with _ -> print_endline "...": If Scanf.sscanf fails to match the pattern, it raises an exception. The with _ block catches any exception and prints a helpful error message.

main_loop (): This is the recursive call. After either printing the sequence or handling an error, main_loop calls itself to repeat the entire process: prompt the user, read the input, and process it.

D. let () = ... (The Entry Point)
This is not a function definition but rather the main executable part of the script. In OCaml, code at the top level is executed in order.

let () = ...: This is a common OCaml idiom to mark the main entry point of a program.

print_endline "--- ... ---": It first prints a welcome banner to the console.

main_loop (): It then makes the initial call to main_loop, which kicks off the interactive loop that is the core of the program's execution.

2. CONCLUSION

The OCaml Fibonacci Sequence script shown in  the previous tutorial  is logically divided into three main functions and an entry point as described in the tutorial above..

3. REFERENCES

Bird, R. (2015). Thinking Functionally with Haskell. Cambridge, England: Cambridge University Press.

Davie, A. (1992). Introduction to Functional Programming Systems Using Haskell. Cambridge, England: Cambridge University Press.

Goerzen, J. & O'Sullivan, B. &  Stewart, D. (2008). Real World Haskell. Sebastopol, CA: O'Reilly Media, Inc.

Hutton, G. (2007). Programming in Haskell. New York: Cambridge University Press.

Lipovača, M. (2011). Learn You a Haskell for Great Good!: A Beginner's Guide. San Francisco, CA: No Starch Press, Inc.

Pierce, Benjamin C., et al., editors. Logical Foundations. Vol. 1 of Software Foundations. Electronic Textbook, 2024. Version 6.7, http://softwarefoundations.cis.upenn.edu.

Thompson, S. (2011). The Craft of Functional Programming. Edinburgh Gate, Harlow, England: Pearson Education Limited.

OCAML FIBONACCI SEQUENCE

 REVISED: Friday, September 12, 2025




1. OCAML  FIBONACCI SEQUENCE

(*
  File: fibonacci_sequence.ml
  Author: Ron Tinnel
  Description: This script provides an interactive command-line interface
  for calculating and displaying a user-defined segment of the Fibonacci sequence.
  It demonstrates core OCaml concepts such as recursion, function definition,
  pattern matching, exception handling, and I/O operations.

  To run this script:
  1. Make sure you have OCaml installed.
  2. Save the code as `fibonacci_sequence.ml`.
  3. Compile it using: `ocamlc -o fib_seq fibonacci_sequence.ml`
  4. Execute the compiled program: `./fib_seq`
*)

(**
 * == Objective 2: Fibonacci Method ==
 * Computes the nth Fibonacci number.
 *
 * OCaml Usage Explained:
 * `let rec fib n`: This defines a recursive function named `fib` that takes one
 * argument, `n`. The `rec` keyword is essential for functions that call themselves.
 * `match n with`: This is OCaml's powerful pattern matching construct. It checks
 * the value of `n` against a series of patterns.
 * `| 0 -> 0`: The first pattern. If `n` is 0, the function returns 0.
 * `| 1 -> 1`: The second pattern. If `n` is 1, the function returns 1. These are
 * the base cases for the recursion, which prevent an infinite loop.
 * `| _ -> fib (n - 1) + fib (n - 2)`: The underscore `_` is a wildcard pattern
 * that matches any other value. If `n` is not 0 or 1, the function calls
 * itself with `n-1` and `n-2` and returns their sum. This is the recursive step.
 *
 * Note: This is a classic, simple implementation. For very large values of `n`,
 * it becomes inefficient due to re-calculating the same Fibonacci numbers
 * multiple times. A more optimized version would use memoization or an
 * iterative approach.
 *
 * @param n The index in the Fibonacci sequence (integer, should be non-negative).
 * @return The nth Fibonacci number.
 *)
let rec fib n =
  match n with
  | 0 -> 0
  | 1 -> 1
  | _ -> fib (n - 1) + fib (n - 2)

(**
 * == Objective 3: Printing the Sequence ==
 * Iterates from a starting number to an ending number, printing the
 * Fibonacci value for each index in the range.
 *
 * OCaml Usage Explained:
 * `let print_fib_sequence start_num end_num =`: Defines a function that takes two arguments.
 * `if start_num < 0 || end_num < 0 then ...`: A simple guard clause to handle invalid
 * negative input, as the Fibonacci sequence is typically defined for non-negative integers.
 * `else if start_num > end_num then ...`: Handles the case where the user mixes up
 * the start and end numbers.
 * `for i = start_num to end_num do ... done`: OCaml provides imperative-style
 * constructs like `for` loops, which are very useful for simple iterations
 * where a side-effect (like printing to the console) is the main goal.
 * `let result = fib i in`: Calls our `fib` function for the current loop index `i`
 * and binds the returned value to the name `result`.
 * `print_endline (...)`: A standard library function that prints a string to the
 * console, followed by a newline character.
 * `string_of_int i`: Converts an integer `i` to its string representation.
 * `^`: The string concatenation operator in OCaml.
 *
 * @param start_num The starting index for the sequence.
 * @param end_num The ending index for the sequence.
 *)
let print_fib_sequence start_num end_num =
  if start_num < 0 || end_num < 0 then
    print_endline "Error: Fibonacci numbers must be non-negative."
  else if start_num > end_num then
    print_endline "Error: The starting number cannot be greater than the ending number."
  else
    (* Loop from the start to the end number, inclusive *)
    for i = start_num to end_num do
      let result = fib i in
      (* Print the result in a formatted string *)
      print_endline ("Fib(" ^ (string_of_int i) ^ ") = " ^ (string_of_int result))
    done

(**
 * == Objective 1: Recursive Main Loop ==
 * This function creates a persistent loop that prompts the user for input,
 * processes it, and then calls itself to repeat the process.
 *
 * OCaml Usage Explained:
 * `let rec main_loop () =`: Defines a recursive function that takes `()` (pronounced "unit")
 * as its argument. Unit is used for functions that don't need a meaningful input,
 * often because they deal with side-effects like I/O.
 * `print_string "> ";`: Prints a prompt without a newline.
 * `flush stdout;`: This is important in interactive programs. It forces the program
 * to immediately print any text that is buffered. Without it, the "> " prompt
 * might not appear until after the user has already entered their input.
 * `let input = read_line () in`: Reads a line of text from the user's input
 * and binds it to the name `input`.
 * `match input with | "exit" -> ...`: We use pattern matching again. If the user
 * types exactly "exit", we print a goodbye message and the function simply returns,
 * ending the chain of recursive calls and thus exiting the program.
 * `| _ -> ...`: If the input is anything other than "exit", we proceed.
 * `try ... with ...`: This is OCaml's exception handling mechanism. We `try` to
 * execute a block of code that might fail (like converting a non-number string to an integer).
 * If an exception occurs, the `with` block catches it.
 * `Scanf.sscanf input "%d %d" print_fib_sequence`: This is a powerful function from the
 * `Scanf` module. It scans the `input` string, looks for a pattern of two integers
 * ("%d %d"), and if it finds them, it passes them as arguments to the `print_fib_sequence`
 * function. It's a very clean way to parse formatted input.
 * `with _ -> ...`: If `Scanf.sscanf` fails (e.g., the user typed "hello world"), it
 * raises an exception. We catch it with a wildcard `_` and print a helpful error message.
 * `main_loop ()`: The crucial final line. After handling the input (either successfully or
 * by catching an error), the function calls itself to start the loop over again.
 * This is how recursion is used to create loops in functional programming.
 *)
let rec main_loop () =
  print_string "Enter a start and end number (e.g., '5 10') or type 'exit': ";
  flush stdout; (* Ensure the prompt is displayed before waiting for input *)
  let input = read_line () in

  match input with
  | "exit" ->
    (* Base case for the recursion: user wants to exit, so we don't recurse. *)
    print_endline "Goodbye!"
  | _ ->
    (* Recursive step: process input, then call main_loop again. *)
    (try
      (* Attempt to parse two integers from the user's input string. *)
      (* If successful, call print_fib_sequence with the parsed numbers. *)
      Scanf.sscanf input "%d %d" print_fib_sequence
    with
    (* If Scanf.sscanf fails, it raises an exception. We catch it here. *)
    | _ -> print_endline "\nInvalid input. Please enter two integers separated by a space.\n");
    main_loop () (* The recursive call that continues the loop *)

(*
 * The entry point of the script.
 * OCaml scripts execute code at the top level from top to bottom.
 * This is the first code that will actually run.
 *)
let () =
  print_endline "--- OCaml Fibonacci Sequence Generator ---";
  main_loop ()

2. CONCLUSION

This script provides an interactive command-line interface  for calculating and displaying a user-defined segment of the Fibonacci sequence.  It demonstrates core OCaml concepts such as recursion, function definition,   pattern matching, exception handling, and I/O operations.

3. REFERENCES

Bird, R. (2015). Thinking Functionally with Haskell. Cambridge, England: Cambridge University Press.

Davie, A. (1992). Introduction to Functional Programming Systems Using Haskell. Cambridge, England: Cambridge University Press.

Goerzen, J. & O'Sullivan, B. &  Stewart, D. (2008). Real World Haskell. Sebastopol, CA: O'Reilly Media, Inc.

Hutton, G. (2007). Programming in Haskell. New York: Cambridge University Press.

Lipovača, M. (2011). Learn You a Haskell for Great Good!: A Beginner's Guide. San Francisco, CA: No Starch Press, Inc.

Pierce, Benjamin C., et al., editors. Logical Foundations. Vol. 1 of Software Foundations. Electronic Textbook, 2024. Version 6.7, http://softwarefoundations.cis.upenn.edu.

Thompson, S. (2011). The Craft of Functional Programming. Edinburgh Gate, Harlow, England: Pearson Education Limited.


Wednesday, September 10, 2025

OCAML MODULE

 REVISED: Thursday, September 11, 2025




1. OCAML MODULE

OCaml modules are a powerful feature for organizing and structuring your code. They allow you to group related definitions (like functions, types, and values) together, control which parts are public or private, and avoid naming conflicts.

Let's break it down using the Adder module from the previous tutorial as an example.

A. The Basic Structure: The Implementation (.ml file)

The fundamental syntax for creating a module is module ModuleName = struct ... end.

  • module ModuleName: This declares a new module. A key rule in OCaml is that module names must start with a capital letter. In the example, this is module Adder.

  • struct ... end: This block contains the implementation of the module. Everything defined between struct and end is part of that module.

In the previous tutorial, the implementation is:

module Adder = struct
  (** Adds two integers and returns the result. *)
  let add (a : int) (b : int) : int = a + b
end

Defined here is a module named Adder that contains a single function named add.

B. Accessing Module Contents

To use a function or value from a module, you use the "dot notation": ModuleName.function_name.

This is exactly what you see later in the main_loop function:

let result = Adder.add num1 num2

This tells the OCaml compiler to look inside the Adder module to find the add function. This prevents naming conflicts. For instance, you could have another module, Subtractor, with its own calculate function, and you would access it via Subtractor.calculate.

C. The Public API: The Interface (.mli file)

While the current script only uses one file (.ml), a crucial part of module programming in OCaml is the concept of an interface or signature. The interface defines which parts of the module are publicly accessible.

  • Interfaces are placed in a file with the same name as the implementation, but with a .mli extension.

  • For the adder.ml file, you could create an adder.mli file.

  • The interface file specifies the types of the values you want to expose, but not their implementation.

An interface for the Adder module would look like this in a file named adder.mli:

(** The public interface for the Adder module. *)
(** Exposes a function that adds two integers.
    @param a The first integer.
    @param b The second integer.
    @return The sum of a and b. *)
val add : int -> int -> int

What this does:

  • val add : int -> int -> int: This line declares that there is a value named add available to the public, and its type is a function that takes an int, then another int, and returns an int.

  • Encapsulation: If there were other "helper" functions inside the Adder module in adder.ml that you did not list in adder.mli, they would be private. Nobody outside the adder.ml file could see or use them. This is the core of encapsulation and information hiding in OCaml.

When you compile your code, the OCaml compiler automatically pairs adder.ml with adder.mli and ensures that the implementation correctly matches the public interface you've defined.

2. CONCLUSION

Define the Implementation: Create a module in your .ml file using module ModuleName = struct ... end. Module names must be capitalized.

Define the Public Interface (Optional but good practice): Create a corresponding .mli file to declare which parts of the module are public using val value_name : type.

Access the Contents: Use dot notation (ModuleName.function_name) to use the public parts of the module from other files or modules.

3. REFERENCES

Bird, R. (2015). Thinking Functionally with Haskell. Cambridge, England: Cambridge University Press.

Davie, A. (1992). Introduction to Functional Programming Systems Using Haskell. Cambridge, England: Cambridge University Press.

Goerzen, J. & O'Sullivan, B. &  Stewart, D. (2008). Real World Haskell. Sebastopol, CA: O'Reilly Media, Inc.

Hutton, G. (2007). Programming in Haskell. New York: Cambridge University Press.

Lipovača, M. (2011). Learn You a Haskell for Great Good!: A Beginner's Guide. San Francisco, CA: No Starch Press, Inc.

Pierce, Benjamin C., et al., editors. Logical Foundations. Vol. 1 of Software Foundations. Electronic Textbook, 2024. Version 6.7, http://softwarefoundations.cis.upenn.edu.

Thompson, S. (2011). The Craft of Functional Programming. Edinburgh Gate, Harlow, England: Pearson Education Limited.



OCAML

 REVISED: Thursday, September 11, 2025




1. OCAML

OCaml is a general-purpose programming language that combines functional, imperative, and object-oriented styles. OCaml belongs to the ML (MetaLanguage) family of languages and is known for its strong type system, expressive syntax, and efficient native code compilation.

2. KEY FEATUES

A. Core Characteristics

Functional programming first-class: Functions are values, higher-order functions are common, and recursion is central.

Strong, static type system: The compiler catches many errors at compile time. Types are inferred, so you rarely need to annotate.

Pattern matching: Powerful way to deconstruct data (like lists, trees, variants) and handle cases safely.

Immutable by default: Values are immutable unless explicitly declared mutable.

Efficient compilation: OCaml compiles to fast native code (via ocamlopt) or bytecode (via ocamlc).

B. Practical Features

Type inference: Lets you write concise code without losing safety.

Algebraic data types: Variants and records make modeling complex data elegant.

Modules and functors: Support modular, large-scale programming.

Garbage collection: Automatic memory management.

Multi-paradigm: You can mix functional, imperative (mutable state, loops), and object-oriented styles.

 C. Why People Use OCaml

Compilers and analyzers: It’s used for projects like Coq, F*, Flow, and the original Rust compiler.

Finance and industry: Some trading systems use it for reliability and performance.

Research and teaching: Clean semantics make it popular in academia.

Static analysis tools: Facebook/Meta’s Infer is written in OCaml.

 D. Compared to Other Languages

vs. Haskell: OCaml is strict (eager evaluation) by default, and more pragmatic with side effects.

vs. Python: OCaml is statically typed and much faster, but has a smaller ecosystem.

vs. C++/Rust: OCaml has less control over memory but far simpler semantics and safer defaults.

3. EXAMPLE
 
(*
  OCaml Adder Script

  This program demonstrates a simple module for integer addition and a main loop
  that continuously prompts the user for two numbers, calculates their sum,
  and prints the result. The program terminates when the user types "exit".
*)

(* 1. A module that adds two integers. *)
module Adder = struct
  (** Adds two integers and returns the result. *)
  let add (a : int) (b : int) : int = a + b
end

(**
 * The main recursive loop of the program. It prompts for user input,
 * processes it, and then calls itself to continue the loop.
*)
let rec main_loop () =
  try
    (* 2. Ask the user to input the value for the two integers. *)
    print_endline "Enter the first integer (or type 'exit' to quit):";
    let input1 = read_line () in

    (* 4. Run in a loop until the user types exit. *)
    if input1 = "exit" then
      (* If the user types 'exit', print a goodbye message and the program will end. *)
      print_endline "Goodbye!"
    else
      begin
        print_endline "Enter the second integer:";
        let input2 = read_line () in

        (* Convert the string inputs to integers.
           This will raise a 'Failure' exception if the input is not a valid integer. *)
        let num1 = int_of_string input1 in
        let num2 = int_of_string input2 in

        (* Call the 'add' function from our 'Adder' module. *)
        let result = Adder.add num1 num2 in

        (* 3. Print the results. Printf.printf allows for formatted output. *)
        Printf.printf "%d + %d = %d\n\n" num1 num2 result;

        (* Call the function again to continue the loop. *)
        main_loop ()
      end
  with
  | Failure _ ->
    (* This block catches errors from 'int_of_string' if the user enters non-numeric input. *)
    print_endline "\nError: Invalid input. Please enter integers only.\n";
    main_loop ()
  | End_of_file ->
    (* This block handles the End of File character (Ctrl+D), gracefully exiting. *)
    print_endline "\nExiting program."

(* The entry point of the program. This initial call starts the main loop. *)
let () = main_loop ()


4. CONCLUSION

OCaml is a high-level, statically typed, functional-first language with strong safety guarantees and efficient performance, well-suited to symbolic computation, compilers, and large-scale reliable systems.

5. REFERENCES

Bird, R. (2015). Thinking Functionally with Haskell. Cambridge, England: Cambridge University Press.

Davie, A. (1992). Introduction to Functional Programming Systems Using Haskell. Cambridge, England: Cambridge University Press.

Goerzen, J. & O'Sullivan, B. &  Stewart, D. (2008). Real World Haskell. Sebastopol, CA: O'Reilly Media, Inc.

Hutton, G. (2007). Programming in Haskell. New York: Cambridge University Press.

Lipovača, M. (2011). Learn You a Haskell for Great Good!: A Beginner's Guide. San Francisco, CA: No Starch Press, Inc.

Pierce, Benjamin C., et al., editors. Logical Foundations. Vol. 1 of Software Foundations. Electronic Textbook, 2024. Version 6.7, http://softwarefoundations.cis.upenn.edu.

Thompson, S. (2011). The Craft of Functional Programming. Edinburgh Gate, Harlow, England: Pearson Education Limited.