listocamlint

building a list of ints in ocaml


I want to write a function that does builds a list between two ints, inclusive

rec myFunc x y would build a list with all the ints between x and y, including x and y

For the logic right now I have something like this:

let rec buildList i n = let x = i+1 in if i <= n then i::(buildList x n)

But this gives me an error "Expression has type 'a list but but an expression was expected of type unit.

I thought buildList is returning a list of ints, and i as an int, so the cons operator would be valid, but its saying it should be void?

Why does this happen, and how do I fix it?


Solution

  • If the condition is true, you return the list i::(buildList x n). If it's not true, what do you return ?

    Add else [] to your function to return the empty list when the condition is not met. When you don't have any else, the compiler supposes it is else () (hence the error message).