Question

If I have a function

let rec function n = 
   if n<0 then [] 
   else n-2 @ function n-2 ;;

I get an error saying that the expression function n-2 is a list of int but it is expecting an int.

How do I concatenate the values to return all the n-2 values above zero as a list?

I cannot use the List module to fold. Thanks

Was it helpful?

Solution

Your title asks how to concatenate lists, but your question seems rather different.

To concatenate lists, you can use the @ operator. In many cases, code that depends on this operator is slower than it needs to be (something to keep in mind for later :-).

Here are some things I see wrong with the code you give:

a. You can't name a function function, because function is a keyword in OCaml.

b. If you use the @ operator, you should have lists on both sides of it. As near as I can see, the thing on the left in your code is not a list.

c. Function calls have higher precedence than infix operators. So myfun n - 2 is parsed as (myfun n) - 2. You probably want something closer to myfun (n - 2).

Even with these changes, your code seems to generate a list of integers that are 2 apart, which isn't what you say you want. However, I can't understand what the function is actually supposed to return.

OTHER TIPS

It seems like you are not concatenating lists, but concatenating ints instead. This is done by the :: operator. So your code would look like:

     else (n-2)::(fun (n-2))

Although I could see this function possibly not producing the desired output if you put in negative numbers. For example if you pass through n = 1, n-2 will evaluate to -1 which is less than zero.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top