0
votes

I need to break a list like [1;2;3;4;5] into [[1;2]; [3;4]; [5]] in OCaml.

I wrote the following function but it is giving me an error (Error: This expression has type 'a list but an expression was expected of type 'a The type variable 'a occurs inside 'a list)

let rec getNewList l =
    match l with 
    [] -> failwith "empty list"
    | [x] -> [x]
    | x::(y::_ as t) -> [x;y] :: getNewList t;;

What am I missing? how can I fix it?

2

2 Answers

1
votes

You want a function of type 'a list -> 'a list list. However, the second branch of your match returns something of type 'a list.

As a side comment, you shouldn't consider it an error if the input is an empty list. There's a perfectly natural answer for this case. Otherwise you'll have a lot of extra trouble writing your function.

1
votes

You're not far from a solution. Three things :

  • if the list is empty, you definitely want your result to be the empty list
  • second case should be [x] -> [[x]]
  • for the main case, how many times should y appear in your result ?