Skip to content

Commit

Permalink
align @immut/list.zip with @array.zip
Browse files Browse the repository at this point in the history
  • Loading branch information
myfreess committed Feb 18, 2025
1 parent 689644a commit 3c82d74
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 14 deletions.
16 changes: 6 additions & 10 deletions immut/list/list.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -480,23 +480,19 @@ pub fn fold_righti[A, B](self : T[A], f : (Int, A, B) -> B, init~ : B) -> B {

///|
/// Zip two lists.
/// If the lists have different lengths, it will return None.
/// If the lists have different lengths, it will return a list with shorter length.
///
/// # Example
///
/// ```
/// let r = @list.zip(@list.of([1, 2, 3, 4, 5]), @list.of([6, 7, 8, 9, 10]))
/// assert_eq!(r, Some(@list.from_array([(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)])))
/// assert_eq!(r, @list.from_array([(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]))
/// ```
pub fn zip[A, B](self : T[A], other : T[B]) -> T[(A, B)]? {
pub fn zip[A, B](self : T[A], other : T[B]) -> T[(A, B)] {
match (self, other) {
(Nil, Nil) => Some(Nil)
(Cons(x, xs), Cons(y, ys)) =>
match zip(xs, ys) {
None => None
Some(ls) => Some(Cons((x, y), ls))
}
_ => None
(Nil, _) => Nil
(_, Nil) => Nil
(Cons(x, xs), Cons(y, ys)) => Cons((x, y), zip(xs, ys))
}
}

Expand Down
2 changes: 1 addition & 1 deletion immut/list/list.mbti
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ impl T {
unsafe_minimum[A : Compare](Self[A]) -> A
unsafe_nth[A](Self[A], Int) -> A
unzip[A, B](Self[(A, B)]) -> (Self[A], Self[B])
zip[A, B](Self[A], Self[B]) -> Self[(A, B)]?
zip[A, B](Self[A], Self[B]) -> Self[(A, B)]
}
impl[X] Default for T[X]
impl[A : Eq] Eq for T[A]
Expand Down
9 changes: 6 additions & 3 deletions immut/list/list_test.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ test "zip" {
let rs = @list.of([6, 7, 8, 9, 10])
inspect!(
ls.zip(rs),
content="Some(@list.of([(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]))",
content="@list.of([(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)])",
)
}

Expand Down Expand Up @@ -607,13 +607,16 @@ test "List::zip with lists of equal length" {
let list1 = @list.of([1, 2, 3])
let list2 = @list.of(["a", "b", "c"])
let zipped = list1.zip(list2)
let expected = Some(@list.of([(1, "a"), (2, "b"), (3, "c")]))
let expected = @list.of([(1, "a"), (2, "b"), (3, "c")])
assert_eq!(zipped, expected)
}

///|
test "@list.zip with empty list" {
inspect!(@list.of([1]).zip((@list.Nil : @list.T[Int])), content="None")
inspect!(
@list.of([1]).zip((@list.Nil : @list.T[Int])),
content="@list.of([])",
)
}

///|
Expand Down

0 comments on commit 3c82d74

Please sign in to comment.