Last active
October 1, 2021 08:44
-
-
Save kmizu/7f95ae9f5c03a78653751293a972ac0e to your computer and use it in GitHub Desktop.
Delayed list in various programming languages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
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)
Prelude> nat = 0 : map (+1) nat
Prelude> take 10 nat
[0,1,2,3,4,5,6,7,8,9]
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