How to define a tree + a pointer to its subtree in OCaml such that adding leaves in this subtree takes constant time?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you want to use purely functional representation, zippers — suggested by nlucaroni — are indeed the good solution to represent a cursor deep down a data structure, that can be moved or used to update the structure.
If you wish for a solution using in-place mutation, you can use mutable data through
mutablerecord fields, or the references (ref) that are derived from it. For example:If you hold an
'a tree_cell, you can mutate it (in constant time).Edit: in the comments of your question, you seem to indicate your interest in a solution for n-ary trees.
The general n-ary case can be represented as
while the zipper solution would look like (untested code)