0

我正在尝试在 OCaml 中创建一个函数,在给定一个 n-tree 的情况下,它返回一个列表,其中包含从叶子到所有分支的根的所有总和。这就是我所做的:

exception NotFound

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

let leaf x = Tr (x, [])

let alb = 
  Tr (1, [Tr (2, [leaf 3; leaf 4; leaf 2]); 
          Tr (5, [leaf 11; leaf 10]); 
          Tr (3, [leaf 9; leaf 7; leaf 10])])

let rec peso (Tr (x, tlist)) =
  match tlist with
    [] -> [x]
  | _ -> [x + peso_l tlist]
and peso_l = function 
    [] -> raise NotFound
  | [t] -> peso t
  | t::rest -> peso t :: peso_l rest

但它不起作用,因为,我认为,

| _ ->[x + peso_l tlist]

返回类似的东西[x+ [t]](我是对的吗?)。我该如何解决?

4

1 回答 1

2

当您编写[x + peso_l tlist]您想要做的事情是添加x到由返回的列表的每个元素中peso_l tlist。这可以通过以下方式实现List.map

exception NotFound

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

let leaf x = Tr (x, [])

let alb =
  Tr
    ( 1,
      [
        Tr (2, [ leaf 3; leaf 4; leaf 2 ]);
        Tr (5, [ leaf 11; leaf 10 ]);
        Tr (3, [ leaf 9; leaf 7; leaf 10 ]);
      ] )

let rec peso (Tr (x, tlist)) =
  match tlist with [] -> [ x ] | _ -> List.map (( + ) x) (peso_l tlist)
and peso_l = function
  | [] -> raise NotFound
  | [ t ] -> peso t
  | t :: rest -> peso t @ peso_l rest

let () =
  Format.printf "@[<v 0>%a@."
    Format.(
      pp_print_list ~pp_sep:pp_print_cut (fun ppf d ->
          Format.fprintf ppf "%d" d))
    (peso alb)
于 2022-02-04T13:16:12.140 回答