如何在OCaml中打印Stack数据结构



任何人都可以告诉如何在OCaml中打印Stack数据结构?内置堆栈类型定义如下:

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

想要打印并保留其元素,这意味着不要使用poppush

最好使用模式匹配来完成问题

代码应该是这样的:

let print_stack stack =???

这看起来可能是家庭作业。你应该展示一些你尝试过但没有成功的东西,并解释为什么你认为它没有成功。这比有人给你答案更有价值。

如果这不是家庭作业:如果你仔细想想,你可以在标准库的另一个地方找到一个好的实现。Stack.iter的实现告诉您在哪里寻找。

函数Stack.iter似乎正是您想要的:

let print_stack print_elem stack = Stack.iter print_elem

在哪里。print_elem打印堆栈中的一个元素。

例如let print_elem_int n = (print_int n; print_newline ())

最终得到答案:

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}
;;

改进版本:

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
;;

最新更新