Skip to content

Instantly share code, notes, and snippets.

@kmizu
Last active October 1, 2021 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmizu/7f95ae9f5c03a78653751293a972ac0e to your computer and use it in GitHub Desktop.
Save kmizu/7f95ae9f5c03a78653751293a972ac0e to your computer and use it in GitHub Desktop.
Delayed list in various programming languages
scala> def from(n: Int): LazyList[Int] = LazyList.cons(n, from(n + 1))
def from(n: Int): LazyList[Int]
scala> from(0).take(10).toList
val res0: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
@kmizu
Copy link
Author

kmizu commented Oct 1, 2021

def foo(n: Int) = n

@kmizu
Copy link
Author

kmizu commented Oct 1, 2021

gosh> (define (from n) (lcons n (from (+ n 1))))
from
gosh> (take (from 0) 10)
(0 1 2 3 4 5 6 7 8 9)

@kmizu
Copy link
Author

kmizu commented Oct 1, 2021

Prelude> nat = 0 : map (+1) nat
Prelude> take 10 nat
[0,1,2,3,4,5,6,7,8,9]

@kmizu
Copy link
Author

kmizu commented Oct 1, 2021

module IList = struct
    type 'a lazy_list = LNil | LCons of 'a * (unit -> 'a lazy_list)

    let rec take n xs = match (n, xs) with
    | 0, xs -> []
    | n, LCons(x, xs) -> x::(take (n - 1) (xs()))
    | _, _ -> failwith "not defined"

    let rec from n = LCons(n, (fun () -> from (n + 1)))
end;;

open IList;;
let nat = from 0;;
print_string (String.concat " " (List.map string_of_int (take 10 nat)));;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment