Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Ocaml, is there a way to implement the function pop of a stack?

Instead of using the module Stack, I want to build a pop function by myself.

The function I implemented is:

let pop (stack_lst:stack) = match stack_lst with
  | [] -> None
  | [x] -> x
  | hd::tl -> hd

Soon I realize that my function only gives the top frame, however, my function does not remove the top frame from the stack. In such a sense, the frame still remains. Since OCaml gives me immutable data structure, what should I do?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In addition to my question, my data type is defined as:

location = Obj of int | Null
and
environment = (var * location) list
and
frame = Decl of environment | Call of environment * stack 
and 
stack = frame list

>Solution :

You’d just have to return a new stack without the popped element as well. Additionally, you’re returning an option if the stack is empty, but not in the other branches, which I’ve also fixed here:

let pop (stack_lst: stack) = match stack_lst with
  | [] -> (None, [])
  | [x] -> (Some x, [])
  | hd::tl -> (Some hd, tl)

or

let pop (stack_lst: stack) = match stack_lst with
  | [] -> None
  | [x] -> Some (x, [])
  | hd::tl -> Some (hd, tl)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading