Discard the first n items in the list

I am trying to create a function that removes the first n elements of a list:

let rec drop nh = if n == 0 then h else (drop n-1 (match h with a::b -> b));; 

This gives:

 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 at OCAML (with functional programming in general), I just follow the guides and tutorials on the Internet. I have no idea what that means.

In addition, it is part of a larger homework that does not require the use of Let, except for the definition of functions, and does not require the use of additional libraries

+4
source share
2 answers

drop n-1 parsed as (drop n) - 1 , you want drop (n-1) .

+6
source

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 (subtracting it from it).

You meant:

 (drop (n-1) (match h with a::b -> b)) 

OCaml compatibility is a bit 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.

+8
source

All Articles