'Drop first n items in a list
I'm trying to make a function which drops the first n items of a list:
let rec drop n h =
if n == 0 then h
else (drop n-1 (match h with a::b -> b));;
This is giving:
Characters 43-49:
if n == 0 then h else (drop n-1 (match h with a::b -> b));;
^^^^^^
Error: This expression has type 'a -> 'b but is here used with type int
What is wrong here? This is my first day in OCAML (with functional programming in general), i'm just following manuals and tutorials on the internet. I've no idea what this message means.
Also, this is a part of a larger homework which requires no use of Let except function definitions, and no use of extra libraries
Solution 1:[1]
drop n-1 is parsed as (drop n) - 1, you want drop (n-1).
Solution 2:[2]
To the compiler, your else case looks like this:
((drop n)-1 (match h with a::b -> b))
The error message means that (drop n) is a function and you are trying to use it as an int (substracting one from it).
You meant:
(drop (n-1) (match h with a::b -> b))
OCaml's associativity is a little surprising at first, but because there are so few syntactic constructs in OCaml, it quickly becomes easy to predict how the compiler will parse a phrase.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sepp2k |
| Solution 2 | Pascal Cuoq |
