Skip to content

Instantly share code, notes, and snippets.

@charlesetc
Created July 30, 2018 02:35
Show Gist options
  • Save charlesetc/ec3f91b5837cb94a1d44838e2d7d451e to your computer and use it in GitHub Desktop.
Save charlesetc/ec3f91b5837cb94a1d44838e2d7d451e to your computer and use it in GitHub Desktop.
Somwhat complex use of objects in OCaml
let rec non_empty_list next prev value =
object (self)
val mutable next = next
val mutable prev = prev
val mutable value = value
method append value =
let l = non_empty_list next (Some self) value in
next <- Some l
method prepend value =
let l = non_empty_list (Some self) prev value in
prev <- Some l
method to_list =
match prev with
| None -> self#to_list'
| Some prev -> prev#to_list
method to_list' =
match next with
| None -> [value]
| Some next -> value :: next#to_list'
end
let () =
let o = non_empty_list None None 2 in
o#append 4;
o#append 6;
o#prepend 0;
o#to_list |> List.iter print_int;
print_endline "\n";
let o = non_empty_list None None "one" in
o#append "two";
o#append "three";
o#prepend "four";
o#to_list |> List.iter print_endline;
@charlesetc
Copy link
Author

Outputs:

0264

four
one
three
two

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment