#!/usr/bin/ruby

#
## Lazy iterators
#

var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13]

## Array
say arr.lazy.grep{.is_even}.map{_**2}.to_a

## Array
arr.lazy.grep{.is_even}.map{_**2}.each { |i|
    say i;
}

## Infinite range
(1..^Inf) -> lazy.grep{.is_even}.first(5).say;

## FileHandle
File(__FILE__).open_r.lazy.grep{.match(/\S/)}.map{.uc}.first(4).join("\n").say;

## DirHandle
Dir.cwd.open_r.lazy.grep{.match(/e/)}.map{.lc}.first(3).join("\n").say

## Infinite range
(^Inf).lazy.grep{.is_prime}.first(10).say;

## Infinite range
(1..^Inf).lazy.map{|i| i + 17 }.map{.fib}.grep{.is_prime}.each { |i|
    say i
    break
}

#
## Lazy type
#

var lz = (^Inf -> lazy.grep{.is_prime})

func f(Lazy foo) {
    var i = foo.iter
    10.times { say i() }
}

f(lz)

var ok = false
try { f("asd") }
catch { ok = true }
assert_eq(ok, true)

assert_eq(^Inf -> lazy.map { polygonal(_, 3) }.first_by { |n|
    n.sigma0 > 10
}, 120)

assert_eq(
    ^Inf -> lazy.map { _**2 + 1 }.grep { .is_prime }.while { _ < 1000 },
    1..1000.isqrt -> map { _**2 + 1}.grep { .is_prime }
)
