Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive function references in OCaml?

Today we learned about "tying the knot" in SML where you have something like this

val tempFunc = ref (fn k:int => true);
fun even x = if x = 0 then true else !tempFunc(x-1);
fun odd x = if x = 0 then false else even(x-1);
tempFunc := odd;

and i'm working with ocaml which is ridiculously similar, but i'm just having trouble kind of doing the same thing. The thing I found that is the closest is

let tempFunc {contents =x}=x;;

but i don't really understand that, and how i could tie that tempFunc to another function. Any help is appreciated!

like image 892
joebro Avatar asked Dec 09 '22 00:12

joebro


1 Answers

The direct translation of your code in OCaml is:

let tempFunc = ref (fun k -> true)
let even x = if x = 0 then true else !tempFunc (x-1)
let odd x = if x = 0 then false else even (x-1)
let () = tempFunc := odd

The idiomatic way to do this (as it is in SML as well) is to use recursive functions:

let rec even x = if x = 0 then true  else odd  (x-1)
and     odd  x = if x = 0 then false else even (x-1)
like image 99
Thomas Avatar answered Jan 09 '23 10:01

Thomas