Skip to content

Commit

Permalink
feat: add rev_map() to @immut/list
Browse files Browse the repository at this point in the history
  • Loading branch information
rami3l authored and bobzhang committed Oct 18, 2024
1 parent e725480 commit 70d8d2a
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
16 changes: 16 additions & 0 deletions immut/list/list.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,22 @@ pub fn mapi[A, B](self : T[A], f : (Int, A) -> B) -> T[B] {
go(self, 0, f)
}

/// Maps the list and reverses the result.
///
/// `list.rev_map(f)` is equivalent to `list.map(f).rev()` but more efficient.
///
/// # Example
/// ```
/// println(@list.of([1, 2, 3, 4, 5]).rev_map(fn(x) { x * 2 }))
/// // output: of([10, 8, 6, 4, 2])
/// ```
pub fn rev_map[A, B](self : T[A], f : (A) -> B) -> T[B] {
loop Nil, self {
acc, Nil => acc
acc, Cons(x, xs) => continue Cons(f(x), acc), xs
}
}

/// Convert list to array.
pub fn to_array[A](self : T[A]) -> Array[A] {
match self {
Expand Down
1 change: 1 addition & 0 deletions immut/list/list.mbti
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ impl T {
rev_concat[A](Self[A], Self[A]) -> Self[A]
rev_fold[A, B](Self[A], ~init : B, (A, B) -> B) -> B
rev_foldi[A, B](Self[A], ~init : B, (Int, A, B) -> B) -> B
rev_map[A, B](Self[A], (A) -> B) -> Self[B]
scan_left[A, E](Self[A], (E, A) -> E, ~init : E) -> Self[E]
scan_right[A, B](Self[A], (A, B) -> B, ~init : B) -> Self[B]
sort[A : Compare + Eq](Self[A]) -> Self[A]
Expand Down
7 changes: 7 additions & 0 deletions immut/list/list_test.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,13 @@ test "mapi" {
inspect!(el.mapi(fn(i, x) { i * x }), content="@list.of([])")
}

test "rev_map" {
let ls = @list.of([1, 2, 3, 4, 5])
let rs : @list.T[Int] = @list.Nil
inspect!(ls.rev_map(fn(x) { x * 2 }), content="@list.of([10, 8, 6, 4, 2])")
inspect!(rs.rev_map(fn(x) { x * 2 }), content="@list.of([])")
}

test "to_array" {
let list = @list.of([1, 2, 3, 4, 5])
let empty : @list.T[Int] = @list.Nil
Expand Down

0 comments on commit 70d8d2a

Please sign in to comment.