As you already saw it, creating a list in OCaml is not so difficult.
But this time, we will see how to iterate through a list and display all elements inside.
We will create two arrays, one of ints, the other of strings.
Once done, we will display their elements.
Let's see it with this OCaml list tutorial.
List of ints:
#let number = [1; 2; 3; 4];;
List of strings:
#let fruits = ["apricot"; "raspberry"; "cherry"; "tomato"];;
List of strings:
(* PRINT LIST STRING *) let rec print_list_string myList = match myList with | [] -> print_endline "This is the end of the string list!" | head::body -> begin print_endline head; print_list_string body end ;;
(* PRINT LIST INT *) let rec print_list_int myList = match myList with | [] -> print_endline "This is the end of the int list!" | head::body -> begin print_int head; print_endline ""; print_list_int body end ;;
# print_list_string fruits;; # print_list_int number;;
apricot raspberry cherry tomato This is the end of the string list! - : unit = () 1 2 3 4 This is the end of the int list! - : unit = ()
A great way to use OCaml for displaying lists!
Add new comment