How to resolve the algorithm Queue/Definition step by step in the OCaml programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Queue/Definition step by step in the OCaml programming language

Table of Contents

Problem Statement

Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion.

Operations:

Errors:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Queue/Definition step by step in the OCaml programming language

Source code in the ocaml programming language

module FIFO : sig
  type 'a fifo
  val empty: 'a fifo
  val push: fifo:'a fifo -> item:'a -> 'a fifo
  val pop: fifo:'a fifo -> 'a * 'a fifo
  val is_empty: fifo:'a fifo -> bool
end = struct
  type 'a fifo = 'a list * 'a list
  let empty = [], []
  let push ~fifo:(input,output) ~item = (item::input,output)
  let is_empty ~fifo =
    match fifo with
    | [], [] -> true
    | _ -> false
  let rec pop ~fifo =
    match fifo with
    | input, item :: output -> item, (input,output)
    | [], [] -> failwith "empty fifo"
    | input, [] -> pop ([], List.rev input)
end


# open FIFO;;
# let q = empty ;;
val q : '_a FIFO.fifo = <abstr>
# is_empty q ;;
- : bool = true
# let q = push q 1 ;;
val q : int FIFO.fifo = <abstr>
# is_empty q ;;
- : bool = false

# let q =
    List.fold_left push q [2;3;4] ;;
val q : int FIFO.fifo = <abstr>

# let v, q = pop q ;;
val v : int = 1
val q : int FIFO.fifo = <abstr>
# let v, q = pop q ;;
val v : int = 2
val q : int FIFO.fifo = <abstr>
# let v, q = pop q ;;
val v : int = 3
val q : int FIFO.fifo = <abstr>
# let v, q = pop q ;;
val v : int = 4
val q : int FIFO.fifo = <abstr>
# let v, q = pop q ;;
Exception: Failure "empty fifo".


  

You may also check:How to resolve the algorithm Inverted syntax step by step in the Perl programming language
You may also check:How to resolve the algorithm Calculating the value of e step by step in the Phix programming language
You may also check:How to resolve the algorithm Sokoban step by step in the Perl programming language
You may also check:How to resolve the algorithm Array concatenation step by step in the Nim programming language
You may also check:How to resolve the algorithm Web scraping step by step in the AutoHotkey programming language