Pascal Triangle in OCaml: Get next line as a list

91 Views Asked by At

I am trying to get an OCaml function which gives the next line of a Pascal's triangle as a list for example:

(next_line: int -> list -> int list)

let get_next_line [1;1] returns [1;2;1] and so on.

I tried something like this but don't know how to go forward:

let rec next_line lst acc = match lst with
| [] -> [1]
| hd::tl -> (* need directions here *)

enter image description here

1

There are 1 best solutions below

0
Chris On

If I have a list [1; 1], how do I get to [1; 2; 1]? Well, imagine if I added 0 to the beginning of the list, then added 0 to the end of the list, so I had two three element lists: [0; 1; 1] and [1; 1; 0].

I could probably write a recursive function or find one in the standard library which adds respective elements of the two lists and gives me [1; 2; 1].

If I could accomplish that, then repeating the same with [1; 2; 1] would give me [0; 1; 2; 1] and [1; 2; 1; 0] and then [1; 3; 3; 1] would be the sum of those two.