Sam
Sam

Reputation: 13

Is it possible to have a Ocaml function that accepts only integer lists?

I'm writing a recursive function in Ocaml that's supposed to count the number of items in an integer list (Yes I know there's a List.length function but I'm trying to do it myself). However the Ocaml compiler/interpreter forces me to use alpha list all the time.

So is it wrong to say that, when a function accepts a list as a parameter, the type of that list must always be alpha? Thanks

EDIT: the reason why it's inconvenient for me to use alpha lists is because i can't compare the head of the alpha list with an integer value due to type-matching complaints

Upvotes: 1

Views: 795

Answers (1)

Chris Conway
Chris Conway

Reputation: 56019

Easy:

 let length (lst : int list) = ...

I'm a bit confused that a comparison is tripping you up; a comparison with an integer should just constrain 'a to be int. For example, in

let length lst = match lst with
  | x :: xs when x = 0 -> ...

lst would have type int list.

Upvotes: 6

Related Questions