2

So I have a recursive function that takes in 2 ints, and a out_channel and basically prints line(a,a+1). It should do this until value of a is equal to b. I.e if a = 1, b = 5

line(1,2) line(2,3) ...line(4,5)

> let rec print_line (out:out_channel)(a:int)(b:int) : unit = if (a < b) then output_string out ("line("^string_of_int(a)^","^string_of_int(a+1)^")\n") > ;; 

I want to make it recursive where it keeps printing the line(a,a+1) until a is no longer less than b. How exactly do I call it again?

Any help would be appreciated.

1 Answer 1

5

So: first check whether a >= b in which case you are done and can return (). Otherwise print one line (the way you did) followed by recursive call to your function, with incremented a. So altogether:

let rec print_line (out:out_channel)(a:int)(b:int) : unit = if a >= b then () else ( output_string out ("line("^string_of_int(a)^","^string_of_int(a+1)^")\n"); print_line out (a + 1) b ) 
Sign up to request clarification or add additional context in comments.

2 Comments

note that you can actually use let rec print_line out a b = as the first line, as the ocaml compiler is smart enough to know what the types of a b and out are.
An if doesn't need an else if the type of the expression is unit. So you can: if a < b then (output_string out ("line("^string_of_int(a)^","^string_of_int(a+1)^")\n"); print_line out (a + 1) b)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.