gens/lazy

================== Lazy List ==================

Types

pub opaque type LazyList(a)

Phantom type for LazyList cat instances

pub type LazyListF

Values

pub fn alternative() -> alternative.Alternative(
  LazyListF,
  LazyList(a),
)

Alternative instance for LazyList

let odd_pears =
  new()
  |> filter(int.is_odd)
  |> map(fn(x) { int.to_string(x) <> " pears" })
let triple_kiwis =
  new()
  |> drop(3)
  |> filter(fn(x) { x % 3 == 0 })
  |> map(fn(x) { int.to_string(x) <> " kiwis" })
// Combining the two lists
let fruits = alternative().or(odd_pears, triple_kiwis)
take(fruits, 8)
// -> ["3 pears", "5 pears", "6 kiwis", "7 pears", "9 pears", "11 pears", "12 kiwis", "13 pears"]
pub fn distinct(la: LazyList(a)) -> LazyList(a)

Filters out duplicate elements of a LazyList

new()
|> map(fn(x) { x / 3 })
|> take(10)
// -> [0, 0, 0, 1, 1, 1, 2, 2, 2, 3]
new()
|> map(fn(x) { x / 3 })
|> distinct()
|> take(5)
// -> [0, 1, 2, 3, 4]
new()
|> map(fn(x) { [x, x + 3] })
|> flatten()
|> distinct()
|> take(10)
// -> [0, 3, 1, 4, 2, 5, 6, 7, 8, 9]
pub fn drop(la: LazyList(a), steps: Int) -> LazyList(a)

Drops the first n elements of a LazyList

new()                   // [0, 1, 2, 3, 4..]
|> drop(4)              // [4, 5, 6, 7..]
|> filter(int.is_even)  // [4, 6, 8..]
|> take(5)
// -> [4, 6, 8, 10, 12]
new()                   // [0, 1, 2, 3, 4..]
|> filter(int.is_even)  // [0, 2, 4, 6, 8..]
|> drop(4)              // [8, 10, 12..]
|> take(5)
// -> [8, 10, 12, 14, 16]
pub fn filter(la: LazyList(a), f: fn(a) -> Bool) -> LazyList(a)

Filters elements from the generated list

new()
|> filter(fn(x) { x % 2 == 0 })
|> filter(fn(x) { x != 4 })
|> take(5)
// -> [0, 2, 6, 8, 10]
pub fn flatten(la: LazyList(List(a))) -> LazyList(a)

Flatten a LazyList of Lists

new()
|> drop(2)
|> map(fn(n) { list.repeat(n, n) })
|> flatten()
|> take(10)
// -> [2, 2, 3, 3, 3, 4, 4, 4, 4, 5]
pub fn list_zip(la: List(a), lb: LazyList(b)) -> List(#(a, b))

Zips a list with an infinite list

["a", "b", "c"] 
|> list_zip(new())
// -> [#("a", 0), #("b", 1), #("c", 2)]
pub fn map(la: LazyList(a), f: fn(a) -> b) -> LazyList(b)

Maps each element of the generated list

new()
|> map(fn(x) { x + 3 })
|> map(int.to_string)
|> take(5)
// -> ["3", "4", "5", "6", "7"]
pub fn new() -> LazyList(Int)

Default LazyList for the list of natural numbers [0..]

new() |> take(5)
// -> [0, 1, 2, 3, 4]
pub fn take(la: LazyList(a), n: Int) -> List(a)

Takes a finite number of elements from a LazyList

take(new(), 5)
// -> [0, 1, 2, 3, 4]
pub fn zip(la: LazyList(a), lb: LazyList(b)) -> LazyList(#(a, b))

Zips two LazyLists into one

  • The resulting index is the maximum of the two takes
  • The filters get combined
  • For separate indexes, do list.zip(take(g1, n), take(g2, n))
let g1 = new() |> map(fn(x) { x + 2 })
let g2 = new() |> filter(int.is_even)
zip(g1, g2)
|> take(3)
// -> [#(2, 0), #(4, 2), #(6, 4)]
Search Document