Advertisement
Guest User

Untitled

a guest
Jul 17th, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 0.70 KB | None | 0 0
  1.   (*A: Masking it as a sequence*)
  2.   type Node<'a> = Empty | Node of 'a * Node<'a>
  3.  
  4.   let cyclic (n:Node<_>) : _ =
  5.     let rn = ref n
  6.  
  7.     let rec next _ =
  8.       match !rn with
  9.       | Empty -> rn := n; next Unchecked.defaultof<_>
  10.       | Node(v, x) -> rn := x; v
  11.  
  12.     Seq.initInfinite next
  13.  
  14.   (*Usage:*)
  15.   let nodes = Node(1, Node(2, Node(3, Empty)))
  16.   cyclic <| nodes |> Seq.take 40 (*val it : seq<int> = seq [1; 2; 3; 1; ...]*)
  17.  
  18.  
  19.  
  20.   (*B: Using lazy*)
  21.   #nowarn "40"
  22.  
  23.   type LNode<'a> = Empty | LNode of 'a * Lazy<LNode<'a>>
  24.  
  25.   let rec x = LNode(1, lazy LNode(2, lazy x))
  26.  
  27.   (*Usage:*)
  28.   let first =
  29.     match x with
  30.     | LNode(1, Lazy(LNode(2,first))) -> first.Value
  31.     | _ -> Empty
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement