"lazy list"

Written By Atticus Kuhn
Tags: "public", "project"
:PROPERTIES: :ID: 8cbd886e-e65b-4fc6-9dcc-58de994a122a :mtime: 20231025023715 :ctime: 20231025023714 :END: #+title: lazy list #+filetags: :public:project: * Lazy List * Implementations of Lazy Lists ** Lazy Lists in [[id:8952459c-5076-4e68-8a68-5f658209f39e][Ocaml]] #+BEGIN_SRC ocaml type 'a seq = | Nil | Cons of 'a * (unit -> 'a seq) #+END_SRC #+RESULTS: : type 'a seq = Nil | Cons of 'a * (unit -> 'a seq) #+BEGIN_SRC ocaml let rec foldseq nil cons = function | Nil -> nil | Cons (x , xs) -> cons x (foldseq nil cons (xs ())) #+END_SRC #+RESULTS: : <fun> #+BEGIN_SRC ocaml let rec view n = if n = 0 then Fun.const [] else function | Nil -> [] | Cons (x , xs) -> x :: (view (n - 1) (xs ())) #+END_SRC #+RESULTS: : <fun> #+BEGIN_SRC ocaml let rec from k = Cons (k , fun _ -> from (k + 1)) #+END_SRC #+RESULTS: : <fun> #+BEGIN_SRC ocaml :exports both view 10 (from 0) #+END_SRC #+RESULTS: | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | #+BEGIN_SRC ocaml :exports both let rec iterate f x = Cons (x , fun _ -> iterate f (f x)) #+END_SRC #+RESULTS: : <fun> #+BEGIN_SRC ocaml let rec filterseq p = function | Nil -> Nil | Cons (x ,xs) -> if p x then Cons (x ,fun _ -> filterseq p (xs())) else filterseq p (xs ()) #+END_SRC #+RESULTS: : <fun> #+BEGIN_SRC ocaml view 20 (filterseq (fun x -> x mod 2 = 0) (from 0)) #+END_SRC #+RESULTS: | 0 | 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34 | 36 | 38 | #+BEGIN_SRC ocaml let next_sqrt a x = (a /. x +. x) /. 2. #+END_SRC #+RESULTS: : <fun> #+BEGIN_SRC ocaml view 10 (iterate (next_sqrt 2.) 5.) #+END_SRC #+RESULTS: | 5 | 2.7 | 1.7203703703703703 | 1.44145536817765 | 1.4144709813677712 | 1.4142135857968836 | 1.4142135623730954 | 1.414213562373095 | 1.414213562373095 | 1.414213562373095 |

See Also

Ocaml

Leave your Feedback in the Comments Section