Sunday, September 14, 2025

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.