TreeZipper 下一个操作 _ vs 完全匹配表达式

问题描述 投票:0回答:1

让以下成为树拉链:

type 'a ntree = Node of 'a * 'a ntree list

type 'a context =
  | Top
  | Context of 'a ntree list * 'a * 'a context * 'a ntree list

type 'a tree_zipper = TZ of 'a context * 'a ntree

let tz1 = TZ (Context (
                [Node ("*", [Node ("a", []); Node ("b", [])])],  (*left siblings in reverse order *)
                "+", (*value of parent node *)
                Top, (*parent's context *)
                []), (*right sibling in order *)
              Node ("*", [Node ("c", []); Node ("d", [])]));;

下一个操作(我的)有什么区别:

let next_exn (TZ (c, t)) = (* on the right, not possible when context is top or right = []*)
  match c with
  | Top -> failwith "right of top node"
  | Context (left, v, up, []) -> failwith "right of last child" (*explain*)
  | Context (left, v, up, r::right) -> TZ (Context (t::left, v, up, right), r)

和提供的解决方案:

let next_exn (TZ (c, t)) = (* on the right, not possible when context is top or right = []*)
  match c with
  | Top -> failwith "right of top node"
  | Context(left, v, up, r::right) -> TZ (Context(t::left, v, up, right), r)
  | _ -> failwith "right of last child"

我假设它们是一样的,但我可能会遗漏一些东西。

另外,为什么我们将

down_exn
中的左兄弟列表设置为
[]
中的:

let down_exn (TZ (c, t)) = 
  match t with (* go to first child *)
  | Node (_, []) -> failwith "down of leaf"
  | Node (v, d::ds) -> TZ (Context([], v, c, ds), d)

?

functional-programming ocaml
1个回答
2
投票

是的,两者实际上是等价的。在

match
表达式中重新排序模式时,请记住它将评估匹配的 first 模式的相应表达式。

这是一个见仁见智的问题,但我当然更喜欢在更复杂的结果之前获得最简单的结果(包括异常或递归基础案例)。基于阅读大量代码,我怀疑我并不孤单。

关于你的第二个问题,如果我们“向下”,我们将“向下”到left-most节点,所以左边不能有兄弟节点。

© www.soinside.com 2019 - 2024. All rights reserved.