Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have 2 functions call each other in OCaml

I want to have 2 different recursive functions in OCaml, where each 1 could call the other one. It isn't working because the one that is declared 1st isn't able to call the one that is declared 2nd. Is there any way to make it work without combining the two functions into 1?

like image 635
Dylan Avatar asked Nov 12 '11 23:11

Dylan


People also ask

Can two functions call each other?

The functions that call itself are direct recursive and when two functions call each other mutually, then those functions are called indirect recursive functions.

How do you call a function in OCaml?

They can be used as a function in ocaml. A function call has the form f arg1 arg2 with function named f , while operator such as + is used in the form arg1 + arg2 . Sometimes it is useful to call operators in the function form, so that the power of function and its syntax fully apply to all operators.

What is tail recursion in OCaml?

The tail recursive function uses an accumulator, a, to store the value of the result of the previous call. This allows OCaml to perform tail call optimization which results in the the stack not overflowing.

Is OCaml recursive?

Dynamic polymorphism is usually combined with recursive data types, but Ocaml modules are not recursive by default.


1 Answers

This is what and is for:

let rec f x = if x < 2 then 1 else x * g (x - 1)
and g x = if x < 2 then 1 else x * f (x - 1)
like image 98
Jeffrey Scofield Avatar answered Sep 18 '22 21:09

Jeffrey Scofield