ocaml - 懒惰列表的 `partition` 实现良好吗?

标签 ocaml

type 'a lazy_list_t = Cons of 'a * (unit -> 'a lazy_list_t)

实现分区功能的最佳/有效方法是什么?

这是我的实现。

let rec filter f (Cons (x, tl_f)) =
  if f x then Cons (x, fun () -> filter f (tl_f()))
  else filter f (tl_f())

let partition f ll = filter f ll, filter (fun x -> f x |> not) ll

我认为它很容易阅读,但缺点是对于每个元素,f实际上应用了两次。

还有什么更好的办法吗?

最佳答案

我会致力于此:

let rec fold_right f ll b =
  match ll with
    [] -> b
  | x :: xs -> f x (fold_right f xs b);;

let partition f ll = 
  let f_split v (tt, ff) = 
    if f v = true then (v::tt,ff) else (tt,v::ff) in 
    fold_right f_split ll ([], []);; 

这样你就可以写出一个惰性的fold_right并最终写出一个惰性的分区函数。 例如这样的事情:

let rec fold_right f (Cons(x, xs)) b =
  f x (fold_right f (xs()) b);;

关于ocaml - 懒惰列表的 `partition` 实现良好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34198975/

相关文章:

arrays - OCaml 中的 a.{X} 是什么意思?

error-handling - 使用 int_of_float 从浮点转换时如何处理 OCaml 中的整数溢出?

ssl - OCaml-ssl with Unix.select 导致读取错误

scala - 使用 Scala、OCaml 和 Haskell 中的类型捕获图形规则

list - 类型 ('a -> ' b) list 的函数 -> OCaml 中的 'a -> ' b list

ocaml - 为什么 OCaml 对多态变体使用子类型化?

functional-programming - 使用 OCAML 中提供的高阶函数检查树是否是 BST

functional-programming - `abstract` 中的 `interface definition` 是什么意思?

ocaml - 在自动制作中抑制 "C source seen but ` CC` undefined”?

ocaml - 删除 OCaml 字符串中最终的尾随 '\n'