Ocaml Map to_seq 用法

Ocaml Map to_seq usage

假设我有以下内容

module IntPairs =
   struct
     type t = int * int
     let compare (x0,y0) (x1,y1) =
       match Stdlib.compare x0 x1 with
           0 -> Stdlib.compare y0 y1
         | c -> c
   end

module PairsMap = Map.Make(IntPairs)

然后我添加了一些元素:

let m = PairsMap.(empty |> add (1,1) 1 |> add (2,1) 1 |> add (1,2) |> add (2,2))

我如何使用 to_seq 按升序打印键? 我不熟悉 ocaml

中的迭代器

这更像是对 OCaml 辅导的请求,而不是关于代码中特定问题的问题。阅读文档通常比在 Whosebug 上提出个别问题更快。

话虽如此,Seq 界面如下所示:

type 'a t = unit -> 'a node
and 'a node = Nil | Cons of 'a * 'a t
val empty : 'a t
val return : 'a -> 'a t
val map : ('a -> 'b) -> 'a t -> 'b t
val filter : ('a -> bool) -> 'a t -> 'a t
val filter_map : ('a -> 'b option) -> 'a t -> 'b t
val flat_map : ('a -> 'b t) -> 'a t -> 'b t
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b t -> 'a
val iter : ('a -> unit) -> 'a t -> unit

如您所见,它提供了许多高阶遍历函数。您想要使用的可能是 iter,因为您想要打印这些值而不是使用它们进行计算。即,没有 return 值可用于您想要的用途。

但是,您应该注意 Map 接口已经具有 iter 功能。据我所知,没有理由在进行迭代之前转换为序列。 Map.iter 文档是这样说的:

The bindings are passed to f in increasing order with respect to the ordering over the type of the keys.

这就是您想要的,所以 Map.iter 似乎可以解决问题。

PairsMap.iter my_print_function m