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

Exercise 2.1.7.1 honour comment #23

Closed
andreas-roehler opened this issue Nov 30, 2023 · 3 comments
Closed

Exercise 2.1.7.1 honour comment #23

andreas-roehler opened this issue Nov 30, 2023 · 3 comments

Comments

@andreas-roehler
Copy link
Contributor

@winitzki commented [...]

In chapter02/worksheets/solution2.1.7.1_AR.scala:

@@ -0,0 +1,17 @@
[...]
+Exercise 2.1.7.1

  • Find all integer pairs 𝑖, 𝑗 where 0 ≀ 𝑖 ≀ 9 and 0 ≀ 𝑗 ≀ 9 and 𝑖 + 4 βˆ— 𝑗 > 𝑖 βˆ— 𝑗.
  • Hint: use flatMap and filter.
  • */

+val a = (0 to 9).flatMap(x => (0 to 9).map { y => (x, y) } )
+val b = a.map{ case x => x._1 + 4 * x._2 }

I would suggest to use case (x, y) => here as well.

@andreas-roehler
Copy link
Contributor Author

andreas-roehler commented Nov 30, 2023

BTW will do that as exercise, however, not convinced WRT rationale behind. Because using pattern match of case seems more generic, that way losing information of the current type in question, which specific tuple-access provides.

@winitzki
Copy link
Owner

The reason is that { case (x, y) => ...} will fail to match (and fail to compile) unless the type is actually a tuple. { case x => ...} will never fail to match.

Suppose you are writing x.map { case x => x._1 + 4 * x._2 } where you expect x to have type Seq[(Int, Int)]. But, by mistake, x has type Seq[(Int, Int, Int)]. Your code with case x will still match and compile but {case (x, y) => ...} will fail to compile and will tell you that the types don't match.

So, writing {case (x, y) => is actually more specific and less generic.

@andreas-roehler
Copy link
Contributor Author

Okay, did a little check with List:

scala> val x = List(9, 3)
x: List[Int] = List(9, 3)

scala> val y = List(5, 6)
y: List[Int] = List(5, 6)

scala> val z = List(x) ++ List(y)
z: List[List[Int]] = List(List(9, 3), List(5, 6))

scala> z.map{ case (i, j) => }
<console>:13: error: constructor cannot be instantiated to expected type;
 found   : (T1, T2)
 required: List[Int]
       z.map{ case (i, j) => }

scala> z.map{ case i => i }
res13: List[List[Int]] = List(List(9, 3), List(5, 6))

scala> z.map{ case List(i, j) => i }
res14: List[Int] = List(9, 5)

andreas-roehler added a commit to andreas-roehler/sofp-solutions that referenced this issue Nov 30, 2023
Signed-off-by: Andreas Roehler <andreas.roehler@online.de>
winitzki added a commit that referenced this issue Nov 30, 2023
#23, Exercise 2.1.7.1 honour comment, pattern-match on tuple
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants