yjasrc
yjasrc

Reputation: 513

How to print a Stack data structure in OCaml

Anyone can tell how to print a Stack data structure in OCaml? The build-in Stack type definition is like :

type 'a t = { mutable c : 'a list }
exception Empty
let create () = { c = [] }
let clear s = s.c <- []
let push x s = s.c <- x :: s.c
let pop s = match s.c with hd::tl -> s.c <- tl; hd | [] -> raise Empty
let length s = List.length s.c
let iter f s = List.iter f s.c

Want to print and keep its elements in place, which means do not use pop and push.

Better to use the pattern matching to complete the problem.

Code should be like:

let print_stack stack =???

Upvotes: 1

Views: 1402

Answers (3)

yjasrc
yjasrc

Reputation: 513

Finally get the answer:

let rec print_s {c=l}=
    match l with
    | [] -> raise Empty
    | [x] -> print_int x; print_string " "
    | h :: ts -> print_int h; print_string " "; print_s {c=ts}
;;

Improved version:

let print_s2 {c=l}=
    let rec print_l list =
        match list with
        | [] -> raise Empty
        | [x] -> print_int x; print_string " "
        | h :: ts -> print_int h; print_string " "; print_l ts
    in
        print_l l
;;

Upvotes: 0

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

This looks like it could be homework. You should show something you've tried that didn't work, and explain why you think it didn't work. This is a lot more valuable that just having somebody give you the answer.

If it's not homework: if you think about it, you can find a good implementation at another place in the standard library. The implementation of Stack.iter tells you where to look.

Upvotes: 3

Thomash
Thomash

Reputation: 6379

It seems like the function Stack.iter does exactly what you want:

let print_stack print_elem stack = Stack.iter print_elem

Where. print_elem prints one element of the stack.

e.g. let print_elem_int n = (print_int n; print_newline ())

Upvotes: 1

Related Questions