Skip to content

Instantly share code, notes, and snippets.

@brendanzab
Last active August 8, 2024 08:43
Show Gist options
  • Save brendanzab/9ed54ca24f3768a3c9d1de5214a67346 to your computer and use it in GitHub Desktop.
Save brendanzab/9ed54ca24f3768a3c9d1de5214a67346 to your computer and use it in GitHub Desktop.
// 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