Ocaml self-esteem

I created type t = Test for int * t ref

How to create any object of type t?

+3
source share
1 answer

As Delnan said, you can use cyclic values:

let rec x = Test (0, ref x)

While recursion is commonly used to define functions, it is possible for certain values. This is not possible at all, there are limitations described in the documentation .

, , : "Test", , "x" , . , , , .., . , ( OCaml " " ), .

, :

let rec x = Test (0, ref x)
let y = Test (1, ref x)
let (Test (_, r)) = x in r := y

let rec x = Test (0, ref y)
and y = Test (1, ref x)

, , " ", Obj. Queue .

, . , "" . int " " (0 , -, ), Queue.

. , , nulloid , :

type t' = Test of int * t' option ref

let x = Test (0, ref None)
let y = Test (0, ref (Some x))

let rec length (Test (_, tail)) =
  match !tail with
  | None -> 0
  | Some tl -> 1 + length tl 

, None . , , .

PS: , , , :

type t = {
  field : int;
  tail : t ref;
 }
+10

Source: https://habr.com/ru/post/1778488/


All Articles