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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With