Reputation: 87
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?
Upvotes: 0
Views: 52
Reputation: 395
You're not far from a solution. Three things :
[x] -> [[x]]
y
appear in your result ?Upvotes: 1
Reputation: 66823
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.
Upvotes: 1