0
votes

I'm trying to make this recursive function which takes an int x and a list, and then removes the first x amount of elements from the list:

let rec nthcdr int_t list_t =
  match int_t with
  | 0 -> list_t 
  | _ -> (match list_t with
          | [] -> [] 
          | h::tail -> nthcdr (int_t -1) tail)
  ;;

but it does not work, h::tail seems to never match, and it always returns []

1
Can't reproduce. How are you testing it? - melpomene
I agree with @melpomene. You code works for me, so maybe it's your test that is flawed. Here's my test: nthcdr 3 [1;2;3;4;5] ==> int list = [4; 5]. - Jeffrey Scofield
my bad guys! I was testing wrongly. - Jose V
It pays to refactor the code so it's more readable (eg. hd::tl instead of h::tail or drop n li instead of whatever the function's name means) before posting or just for your own sanity. - Pie 'Oh' Pah

1 Answers

1
votes

I'd like to offer improvement to the code as an answer (since OP had already found the solution).

It feels redundant to pattern match an integer int_t. You can do it of course, but the benefit of pattern-matching becomes apparent when used with algebraic data types like records or variants or collections like lists. Also, using if..else for the integer makes code cleaner and differentiate the base case from the inductive cases.

let rec drop n li =
  if n = 0 then li else
  match li with
  | [] -> [] 
  | h::t -> drop (n-1) t