Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

solution2.5.2.4.scala provided #72

Merged
merged 1 commit into from
Oct 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions chapter02/worksheets/solution2.5.2.4.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
Exercise 2.5.2.4

For a, b, c of type Set[Int],
compute the set of all sets of the form Set(x, y, z)
where x is from a, y from b, and z from c.

The required type signature and a sample test:

def prod3(a: Set[Int], b: Set[Int], c: Set[Int]): Set[Set[Int]] = ???

scala> prod3(Set(1, 2), Set(3), Set(4, 5))
res0: Set[Set[Int]] = Set(Set(1,3,4), Set(1,3,5), Set(2,3,4), Set(2,3,5))

Hint: use flatMap.
*/

def prod3(a: Set[Int], b: Set[Int], c: Set[Int]): Set[Set[Int]] = {
val d = List(a, b, c)
d(0).flatMap{ x => d(1).flatMap{ y => d(2).map{ z => Set(x, y, z) }}}
}

val result = prod3(Set(1, 2), Set(3), Set(4, 5))
val expected: Set[Set[Int]] = Set(Set(1,3,4), Set(1,3,5), Set(2,3,4), Set(2,3,5))
assert(result == expected)

// scala> :load solution2.5.2.4.scala
// :load solution2.5.2.4.scala
// def prod3(a: Set[Int], b: Set[Int], c: Set[Int]): Set[Set[Int]]
// val result: Set[Set[Int]] = Set(Set(1, 3, 4), Set(1, 3, 5), Set(2, 3, 4), Set(2, 3, 5))
// val expected: Set[Set[Int]] = Set(Set(1, 3, 4), Set(1, 3, 5), Set(2, 3, 4), Set(2, 3, 5))

Loading