Last active
August 8, 2024 08:43
-
-
Save brendanzab/9ed54ca24f3768a3c9d1de5214a67346 to your computer and use it in GitHub Desktop.
Iterators in gleam (responding to https://lobste.rs/s/3boto7/first_impressions_gleam_lots_joys_some#c_rtqsgu)
This file contains 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
// WARNING: I have never programmed in gleam before and this is probably | |
// considered very unideomatic/cursed. You have been warned! :P | |
import gleam/io | |
import gleam/option.{type Option, None, Some} | |
type Iterator(a) { | |
Iterator(next: fn () -> Option(#(a, Iterator(a)))) | |
} | |
fn list_iterator(xs: List(a)) -> Iterator(a) { | |
Iterator(fn() { | |
case xs { | |
[] -> None | |
[x, ..xs] -> Some(#(x, list_iterator(xs))) | |
} | |
}) | |
} | |
fn map(xs: Iterator(a), f: fn(a) -> b) -> Iterator(b) { | |
Iterator(fn() { | |
case xs.next() { | |
None -> None | |
Some(#(x, xs)) -> Some(#(f(x), map(xs, f))) | |
} | |
}) | |
} | |
fn collect_list(xs: Iterator(a)) -> List(a) { | |
case xs.next() { | |
None -> [] | |
Some(#(x, xs)) -> [x, ..collect_list(xs)] | |
} | |
} | |
pub fn main() { | |
let xs = | |
list_iterator([1, 2, 3]) | |
|> map(fn(x) { x * x }) | |
|> collect_list | |
io.debug(xs) // [1, 4, 9] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment