Skip to content

Instantly share code, notes, and snippets.

@ClarkeRemy
Last active April 3, 2025 10:33
Show Gist options
  • Save ClarkeRemy/790fb4fc7bf233c258ccd4bf2a7a99e4 to your computer and use it in GitHub Desktop.
Save ClarkeRemy/790fb4fc7bf233c258ccd4bf2a7a99e4 to your computer and use it in GitHub Desktop.
Ocaml abstract list
type 'a list= List of { l : 'z . (unit -> 'z) -> ('a * 'a list -> 'z) -> 'z }
let nil : 'a list = List{ l = fun f -> fun _ -> f()}
let cons (v : 'a) (r : 'a list) : 'a list=
List{ l = fun _ -> fun f -> f(v,r) }
let ex : int list = cons 3 (cons 1 (cons 2 nil))
let length (l : 'a list) : int =
let rec loop (List{l}) acc = (l[@tailcall]) nil (cons loop) acc
and nil () acc = acc
and cons fix (_,r) acc = (fix[@tailcall]) r (1 + acc)
in loop l 0
let () = Printf.printf "%d\n" (length ex)
type 'a list= List of { l : 'z . (unit -> 'z) -> ('a * 'a list -> 'z) -> 'z }
let nil : 'a list = List{ l = fun f -> fun _ -> f()}
let cons (v : 'a) (r : 'a list) : 'a list=
List{ l = fun _ -> fun f -> f(v,r) }
let ex : int list = cons 3 (cons 1 (cons 2 nil))
let len_nil () acc = acc
let len_cons fix (_,r) acc = (fix[@tailcall]) r (1 + acc)
let rec loop (List{l}) acc = (l[@tailcall]) len_nil (len_cons loop) acc
let length (l : 'a list) : int = loop l 0
let () = Printf.printf "%d\n" (length ex)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment