Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop first n items in a list

Tags:

ocaml

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

like image 735
lalli Avatar asked Dec 07 '22 01:12

lalli


1 Answers

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.

like image 102
Pascal Cuoq Avatar answered Jan 05 '23 00:01

Pascal Cuoq