Created
July 30, 2018 02:35
-
-
Save charlesetc/ec3f91b5837cb94a1d44838e2d7d451e to your computer and use it in GitHub Desktop.
Somwhat complex use of objects in OCaml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Outputs: