From b8af54a93535409d6dda2850dda29d87518fb192 Mon Sep 17 00:00:00 2001 From: versecafe <147033096+versecafe@users.noreply.github.com> Date: Wed, 11 Sep 2024 00:54:20 -0500 Subject: [PATCH] Allow cartesian product of (a, b) instead of (a, a) --- src/gleam_community/maths/combinatorics.gleam | 6 +++--- test/gleam_community/maths/combinatorics_test.gleam | 9 ++++++++- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/gleam_community/maths/combinatorics.gleam b/src/gleam_community/maths/combinatorics.gleam index b6a6606..726ae52 100644 --- a/src/gleam_community/maths/combinatorics.gleam +++ b/src/gleam_community/maths/combinatorics.gleam @@ -652,10 +652,10 @@ fn do_list_permutation_with_repetitions( /// /// /// -pub fn cartesian_product(xset: set.Set(a), yset: set.Set(a)) -> set.Set(#(a, a)) { +pub fn cartesian_product(xset: set.Set(a), yset: set.Set(b)) -> set.Set(#(a, b)) { xset - |> set.fold(set.new(), fn(accumulator0: set.Set(#(a, a)), member0: a) { - set.fold(yset, accumulator0, fn(accumulator1: set.Set(#(a, a)), member1: a) { + |> set.fold(set.new(), fn(accumulator0: set.Set(#(a, b)), member0: a) { + set.fold(yset, accumulator0, fn(accumulator1: set.Set(#(a, b)), member1: b) { set.insert(accumulator1, #(member0, member1)) }) }) diff --git a/test/gleam_community/maths/combinatorics_test.gleam b/test/gleam_community/maths/combinatorics_test.gleam index 087122f..729f450 100644 --- a/test/gleam_community/maths/combinatorics_test.gleam +++ b/test/gleam_community/maths/combinatorics_test.gleam @@ -72,7 +72,7 @@ pub fn int_combination_test() { combinatorics.combination(7, 5, option.Some(combinatorics.WithRepetitions)) |> should.equal(Ok(462)) - // NOTE: Tests with the 'combination' function that produce values that exceed + // NOTE: Tests with the 'combination' function that produce values that exceed // precision of the JavaScript 'Number' primitive will result in errors } @@ -697,4 +697,11 @@ pub fn example_test() { |> should.equal( set.from_list([#(1.0, 1.0), #(1.0, 2.0), #(10.0, 1.0), #(10.0, 2.0)]), ) + + // Cartesian product of two sets with different types + set.from_list(["1", "10"]) + |> combinatorics.cartesian_product(set.from_list([1.0, 2.0])) + |> should.equal( + set.from_list([#("1", 1.0), #("1", 2.0), #("10", 1.0), #("10", 2.0)]), + ) }