-1

I'm trying to make a function in OCaml where, given a n-tree, it returns a list of all the sums from leaf to root of all the branches. This is what i did:

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

But it doesn't work because, I think,

| _ ->[x + peso_l tlist]

returns something like [x+ [t]] (am I right?). How can I fix it?

Chris
  • 26,361
  • 5
  • 21
  • 42
  • For a given node `n`, use a `List.fold_left` to sum the result of `peso` for all its childs – Butanium Feb 04 '22 at 13:06
  • 1
    This question would be improved with a sample of the expected output, and any errors you received trying to use your code. There are a lot of smart people here, so they can probably figure it out, but making it easier for them to figure it out will probably get you more and better answers. – Chris Feb 04 '22 at 15:35

1 Answers1

2

When you write [x + peso_l tlist] what you want to do is add x to each element of the list returned by peso_l tlist. This can be achieved with 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)
Lhooq
  • 4,281
  • 1
  • 18
  • 37
  • I was thinking of List.map too, but i had no idea what @ was so i still had errors...thank you – Leonardo Moreo Feb 04 '22 at 13:36
  • You're welcome. When you work with a module you don't know, remember to open its documentation. If you don't care about order, List.rev_append is better than @ by the way – Lhooq Feb 04 '22 at 15:18