Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can (1 +) be ever a function?

Tags:

scala

I am new to Scala, and trying to understand the following codes (derived from an example in the Beginning Scala book)

scala> def w42(f: Int => Int) = f(42)  //(A)
w42: (f: Int => Int)Int

scala> w42 (1 +)      //(B)
res120: Int = 43

I do not understand how "1 +" at point (B) is consider as a function (take 1 Int parameter, and return an Int) that satisfies the w42 definition at point (A)?

Would you mind please explain or point me to some documents that have the answer?

like image 553
lastrinh1296773 Avatar asked Apr 03 '12 06:04

lastrinh1296773


People also ask

What is a 1 function?

What is an Example of a One to One Function? The function f(x) = x + 5 is a one to one function as it produces different output for a different input x. And for a function to be one to one it must return a unique range for each element in its domain. Here, f(x) returns 6 if x is 1, 7 if x is 2 and so on.

What determines if a function is 1 to 1?

If the graph of a function f is known, it is easy to determine if the function is 1 -to- 1 . Use the Horizontal Line Test. If no horizontal line intersects the graph of the function f in more than one point, then the function is 1 -to- 1 .

How do you know if it is a one to many function?

A function is said to be one-to-one if every y value has exactly one x value mapped onto it, and many-to-one if there are y values that have more than one x value mapped onto them. This graph shows a many-to-one function.

Is the inverse of a function always a function?

The inverse of a function may not always be a function! The original function must be a one-to-one function to guarantee that its inverse will also be a function. A function is a one-to-one function if and only if each second element corresponds to one and only one first element. (Each x and y value is used only once.)


1 Answers

Simple. In Scala 1 + 2 is just a syntax sugar over 1.+(2). This means Int has a method named + that accepts Int:

final class Int extends AnyVal {
  def +(x: Int): Int = //...
  //...
}

This is why you can use 1 + as if it was a function. Example with less unexpected method naming:

scala> def s42(f: String => String) = f("42")
s42: (f: String => String)String

scala> s42("abc".concat)
res0: String = abc42

BTW Technically speaking, eta-expansion is also involved to convert method to a function.

like image 195
Tomasz Nurkiewicz Avatar answered Nov 04 '22 10:11

Tomasz Nurkiewicz