简体   繁体   English

折叠在OCaml的树

[英]Folding over Trees in OCaml

This is my attempt of implementing fold (left) for the tree (it is very simplified version, but carefully reproduces real tree structure): 这是我为树实现fold (左)的尝试(它是非常简化的版本,但仔细地再现了真实的树结构):

type 'a tree = Leaf of 'a | Node of 'a * 'a tree list

let rec fold t acc f =
  match t with
  | Leaf x -> f acc x None
  | Node (x, lst) ->
    let deferred acc =
      List.fold_left (fun acc t' -> fold t' acc f) acc lst in
    f acc x (Some deferred)

The idea is to use deferred call for subtrees. 我们的想法是使用延迟调用子树。 It lets us: 它让我们:

  • skip a subtree traversing if needed 如果需要,跳过子树遍历
  • initialize a subtree traversing and compose results 初始化子树遍历并撰写结果

A toy example: 玩具示例:

open Printf

let () =
  let tree = Node (3, [Leaf 5; Leaf 3; Node (11, [Leaf 1; Leaf 2]); Leaf 18]) in

  fold tree "" (fun str x nested ->
      let plus str = if String.length str = 0 then "" else "+" in
      let x = string_of_int x in
      match nested with
      | None -> str ^ (plus str) ^ x
      | Some f -> str ^ (plus str) ^ x ^ "*(" ^ (f "") ^ ")"
    )
  |> printf "%s=";

  fold tree 0 (fun acc x -> function
      | None -> acc + x
      | Some f -> x * (f 0) + acc
    )
  |> printf "%d\n";

I guess this was invented many times already. 我想这已经发明了很多次了。 Is there any name for this technique? 这种技术有什么名字吗? Any well-known canonic form? 任何着名的狂热形式? Any ideas how to make it better? 任何想法如何使它更好?

A more canonical will be to define a lazy data structure. 更典型的是定义一个惰性数据结构。 Possibly like this: 可能是这样的:

type 'a tree = unit -> 'a tr
and 'a tr = Stem of 'a * 'a tree list

Or, you can try OCaml's lazy values. 或者,您可以尝试OCaml的惰性值。

Trying to lazily traverse a non-lazy data structure is not very canonic, IMO. 试图懒洋洋地遍历一个非懒惰的数据结构并不是非常规范,IMO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM