ocaml

OCaml - a function which returns all the prefixes of a list


For [1;2;3] , I want to return [[]; [1]; [1; 2]; [1; 2; 3]] . I have hit a wall and i need help, this is what i have done so far

let rev list =
  let rec aux acc = function
    | [] -> acc
    | h::t -> aux (h::acc) t in
  aux [] list

let prefixes xs = 
  let xs = rev xs in
  let rec xs = function
    | [] -> [[]]
    | hd::tl -> xs::tl in
  xs

Please help me, I know that probably most of what i have done so far is wrong.


Solution

  • Here's a solution I found. Although it's probably not the best since I need to reverse the list at the end.

    let prefix l = List.rev (List.fold_left (fun acc itt -> ((List.hd acc)@[itt])::acc) [[]] l);;