开发者

Ocaml: calling recursive function again

开发者 https://www.devze.com 2023-02-21 20:39 出处:网络
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

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 a开发者_C百科ppreciated.


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
  )
0

精彩评论

暂无评论...
验证码 换一张
取 消