0

When I read the book 《Functional Programming in scala》. I find the expression like this:

case (Cons(h, t), Empty) => 
    Some(f(Some(h()), Option.empty[B]) -> (t(), empty[B]))

What's the difference between

Some(f(Some(h()), Option.empty[B]), (t(), empty[B]))
jwvh
  • 50,871
  • 7
  • 38
  • 64
  • 1
    (1 -> 2), (1, 2) is the same type (Int, Int) = (1,2), so it's just for look bueatifully? – 八斗风流 Jul 29 '18 at 03:16
  • Have a look at https://stackoverflow.com/questions/7888944/what-do-all-of-scalas-symbolic-operators-mean. – Don Branson Jul 29 '18 at 03:24
  • Thanks for your help! I think I understand this! The ArrowAssoc is the implicit class and 1 -> 2 actually is Predef.ArrowAssoc(1).->(2) and it returns the result (1, 2). It's just for analysis! – 八斗风流 Jul 29 '18 at 03:53

2 Answers2

1

If your 2nd example compiles, it should compile with a warning: creating a 2-tuple: this may not be what you want Otherwise it would fail because Some() doesn't take two parameters. The 1st example should compile because the -> is explicitly creating the tuple to send as a single parameter to the (outer) Some().

When creating a tuple of two elements you have the option of using parentheses and comma (5, true), or the arrow 5 -> true. In most situations the parentheses are optional when using the arrow version.

The arrow can't be used if you want more than 2 elements (i.e. not nested tuples):

'c' -> 'b' -> 'x'
//res0: ((Char, Char), Char) = ((c,b),x)
jwvh
  • 50,871
  • 7
  • 38
  • 64
  • It will compile, actually, as the compiler translates `Some(1, 2)` into `Some((1, 2))`, absent the [`-Yno-adapted-args`](https://docs.scala-lang.org/overviews/compiler-options/index.html) compiler flag. – Brian McCutchon Jul 29 '18 at 03:45
  • @BrianMcCutchon; Hmm, you're right about `Some(1,2)` but my REPL session threw an error with the original example code. Answer adjusted accordingly. – jwvh Jul 29 '18 at 03:54
  • Interesting, I don't even get a warning in the Scala 2.12.4 repl. Of course, I can't compile the OP's code as is because some definitions are missing. – Brian McCutchon Jul 29 '18 at 04:01
0

The -> is actually a method of the ArrowAssoc class to which every object can be implicitly converted. See the object scala.Predef. It is defined as:

def -> [B](y: B): Tuple2[A, B] = Tuple2(x, y)

This means that 1 -> 2 is equivalent to 1.->(2) which evaluates to Tuple2(1, 2). This is also explained in section 21.4 of the book (3rd edition).

Vincent
  • 1,126
  • 2
  • 10
  • 11