Ocaml linked list

How to create a linked list to store my data in Ocaml? I am trying to create a separate list, but I am having problems with the syntax. I just want to create a module to just get 'a from the linked list, insert' a or delete 'a.

Does anyone have an idea?

Thank you, Faisal Abid

+4
source share
3 answers

As aneccodeal said, ocaml already has lists.

However, for your interest, you can create your own list. Obviously, you will never use it in a real application :) If you want to have several trees, the data structure will be very similar.

exception Empty_list type 'a my_list = Nil | List of 'a * 'a my_list let head = function Nil -> raise Empty_list | List(e,_) -> e;; let tail = function Nil -> Nil | List(_,t) -> t let l = List(1, List(4, List(8, Nil)));; print_endline (string_of_int(head l));; print_endline (string_of_int (head(tail l)));; 
+8
source

OCaml has built-in lists:

The list of integers: [1; 2; 3; 4; 5]; return: int list = [1; 2; 3; 4]

List of strings: ["this"; “what”, “other”] ;; return: string list = ["this"; "what"; "Other"]

Or you can use cons-cons :: to create lists:

1 :: 2 :: 3 :: [] ;; return: int list = [1; 2; 3]

To get the title (first element) of a list:

List.hd [1; 2; 3]
returns 1

To get the tail of the list (all items after the first item)

List.tl [1; 2; 3] return: int list = [2; 3]

In addition, you can see how the lists are implemented in the standard OCaml library by looking at:

[installation location for OCaml] /lib/ocaml/std-lib/list.ml

+5
source

Does OCaml have lists as primitives? I have not done SML since college, but I seem to recall the head and tail primitives. I see that other people have implemented a data structure with a true linked list, though ... check out the Dustin OCaml Linkedlist , for example.

+4
source

All Articles