Newbie scala confused about identiy type signature, and nothing (bottom) - scala

I'm best described as a C#/F# + a bit of amateur Haskell programmer.
I'm a bit confused about the type signatures in Scala.
for example
the identity function has type
Nothing => Nothing
(according to scala console in my intellij thing)
but to me that makes no sense.
the type of identity is something like..
all x . x => x
.....
so
identity 1
=> x ~ Int
=> 1 : Int
Nothing => Nothing
makes no sense to me....I would expect I type exception when passing any value to a function expecting Nothing!
clearly Im missing something.

In scala there is a distinction between methods and function values. Methods can be parameterized, while values (function or otherwise) can not.
So the identity method looks like this:
def identity[A](x: A): A = x
It has type [A](x: A)A. But if you convert it to a function value like this:
val idFunction = identity _
The value idFunction will have type Nothing => Nothing. Since I didn't provide a type argument to identity the compiler inferred A = Nothing.
What you can do is this:
val intIdentity = identity[Int] _
And then intIdentity will have type Int => Int.

The identity function is defined in scala.PreDef and has the following type signature:
def identity[A](x: A): A
It takes a type parameter A, a value of type A, and returns what it got as an input.
See the docs for scala.PreDef here: scala.Predef

Related

Scala understanding signatures

In Scala (Play Framework), I can't understand the type signatures even though I read through all the symbols in here.
For example:
/* matches if a == b */
def equalTo[T](t: => T): BeEqualTo
class BeEqualTo(t: => Any)
extends BeTypedEqualTo[Any]
What on earth do these type signatures even mean?
For example, what exactly is "a" and "b" in the documentation? All I see is "t". Is equalTo a function that takes in a function which returns a value of generic type T?
Another example...
Say I have this line...
status(home).must(equalTo(OK))
According to the IDE, OK is a pattern or symbol of type Int. So OK is an Int? You can monkey-patch an int to give it a function like "must", but how can an Int go inside of "equalTo", a function that takes in a function?
Now some of the type signatures make sense. For example...
def status(of: Future[Result])(implicit timeout: Timeout): Int
^ This is a curried function that takes in a future that returns something of type Result and that sucks in an implicit parameter of type Timeout from somewhere (Scala magic) and returns an Int. "home" is of type "Future[Result]", so it fits inside "status".
But other stuff...
contentType(home).must(beSome.which(_ == "text/html"))
^ My IDE says that beSome is of type
def beSome[T](check: ValueCheck[T]): SomeCheckedMatcher[T]
^ So "beSome" is a function. If that is the case, then how on earth can I appeand ".which()", another function, to it as if it were an object?
Another example...
def which[R : AsResult](f: (U) => R): OptionLikeCheckedMatcher[F, Nothing, U]
^ How on earth do you read these type signatures? "which" takes in "f: (U)", or a variable which we call "f" of type "(U)"? Why the unnecessary parenthesis around the "(U)"? Can't you just say "f: U" and make U be a String if R is a String?
"must" is like this...
def must(m: => Matcher[T]): MatchResult[T]
^ So "must" takes in a function that returns a Matcher. But "which" is passing in an OptionLikeCheckedMatcher. "m: => Matcher[T]" is a function that takes in an "m" and returns a "Matcher[T]". How is that the same as an object of type OptionLikeCheckedMatcher?
Can someone provide a definitive guide as to how to read Scala type signatures?
I think you're getting a little confused with the distinction between a function-valued parameter and a call-by-name parameter. They are similar but not quite the same. In the first example you posted, def equalTo[T](t: => T): BeEqualTo, the : => notation means that the parameter is not evaluated immediately (as it would be if it were declared with just a colon), but every time it is used in an expression. This link might clarify things a bit for you: https://tpolecat.github.io/2014/06/26/call-by-name.html
In another example you posted, def which[R: AsResult](f: (U) => R): OptionCheckedLikeMatcher[F, Nothing, U] takes in a function parameter called f, which accepts a U as its argument and returns a T. The brackets around the U are indeed unnecessary, but they would have been necessary if (for example) f were a function taking 2 parameters of type U - we would then have written it as f: (U, U) => R. The return value of which will be an OptionCheckedMatcher. Assuming that this is a subtype of Matcher (which seems sensible), this is the value which is passed to must.

Strange implicit def with function parameter behaviour in Scala

I've written a simple code in Scala with implicit conversion of Function1 to some case class.
object MyApp extends App{
case class FunctionContainer(val function:AnyRef)
implicit def cast(function1: Int => String):FunctionContainer = new FunctionContainer(function1)
def someFunction(i:Int):String = "someString"
def abc(f : FunctionContainer):String = "abc"
println(abc(someFunction))
}
But it doesn't work. Compiler doesn't want to pass someFunction as an argument to abc. I can guess its reasons but don't know exactly why it doesn't work.
When you use a method name as you have, the compiler has to pick how to convert the method type to a value. If the expected type is a function, then it eta-expands; otherwise it supplies empty parens to invoke the method. That is described here in the spec.
But it wasn't always that way. Ten years ago, you would have got your function value just by using the method name.
The new online spec omits the "Change Log" appendix, so for the record, here is the moment when someone got frustrated with parens and introduced the current rules. (See Scala Reference 2.9, page 181.)
This has not eliminated all irksome anomalies.
Conversions
The rules for implicit conversions of methods to functions (§6.26) have been tightened. Previously, a parameterized method used as a value was always implicitly converted to a function. This could lead to unexpected results when method arguments were forgotten. Consider for instance the statement below:
show(x.toString)
where show is defined as follows:
def show(x: String) = Console.println(x)
Most likely, the programmer forgot to supply an empty argument list () to toString. The previous Scala version would treat this code as a partially applied method, and expand it to:
show(() => x.toString())
As a result, the address of a closure would be printed instead of the value of s. Scala version 2.0 will apply a conversion from partially applied method to function value only if the expected type of the expression is indeed a function type. For instance, the conversion would not be applied in the code above because the expected type of show’s parameter is String, not a function type. The new convention disallows some previously legal code. Example:
def sum(f: int => double)(a: int, b: int): double =
if (a > b) 0 else f(a) + sum(f)(a + 1, b)
val sumInts = sum(x => x) // error: missing arguments
The partial application of sum in the last line of the code above will not be converted to a function type. Instead, the compiler will produce an error message which states that arguments for method sum are missing. The problem can be fixed by providing an expected type for the partial application, for instance by annotating the definition of sumInts with its type:
val sumInts: (int, int) => double = sum(x => x) // OK
On the other hand, Scala version 2.0 now automatically applies methods with empty parameter lists to () argument lists when necessary. For instance, the show expression above will now be expanded to
show(x.toString())
Your someFunction appears as a method here.
You could try either
object MyApp extends App{
case class FunctionContainer(val function:AnyRef)
implicit def cast(function1: Int => String):FunctionContainer = new FunctionContainer(function1)
val someFunction = (i:Int) => "someString"
def abc(f : FunctionContainer):String = "abc"
println(abc(someFunction))
}
or
object MyApp extends App{
case class FunctionContainer(val function:AnyRef)
implicit def cast(function1: Int => String):FunctionContainer = new FunctionContainer(function1)
def someFunction(i:Int): String = "someString"
def abc(f : FunctionContainer):String = "abc"
println(abc(someFunction(_: Int)))
}
By the way: implicitly casting such common functions to something else can quickly lead to problems. Are you absolutely sure that you need this? Wouldn't it be easier to overload abc?
You should use eta-expansion
println(abc(someFunction _))

Scala: Why does function need type variable in front?

From working on the first problem of the 99 Scala Puzzles I defined my own version of last like so:
def last[A](xs: List[A]): A = xs match {
case x :: Nil => x
case x :: xs => last(xs)
}
My question is: Why is it necessary for last to be directly followed by the type variable, as in last[A]? Why couldn't the compiler just do the right thing if I wrote the function like so:
def last(xs: List[A]): A
.....
(leaving the [A] off the end of last[A]?)
And if the compiler is capable of figuring it out, then what is the rationale for designing the language this way?
A appears 3 times:
last[A]
List[A]
: A(after the argument list)
The 2nd one is needed to specify that the List contains objects of type A. The 3rd one is needed to specify that the function returns an object of type A.
The 1st one is where you actually declare A, so it could be used in the other two places.
You need to write last[A] because A does not exist. Since it does not exist, by declaring it after the name of the function you actually get a chance to define some expectations or constraints for this type.
For example: last[A <: Int] to enforce the fact that A has to be a subtype of Int
Once it's declared, you can use it to define the type of your parameters and your return type.
I got an insight from #Lee's comment:
How would the compiler know that the A in List[A] doesn't refer to an
actual type called A?
To demonstrate to myself that this made sense, I tried substituting the type variable A, with the name of an actual type String, and then passed the function a List[Int], seeing that when last is declared like def last[String](xs: List[String]): String, I was able to pass last a List[Int]:
scala> def last[String](xs: List[String]): String = xs match {
| case x :: Nil => x
| case x :: xs => last(xs)
| }
last: [String](xs: List[String])String
scala> last(List(1,2,3,4))
res7: Int = 4
Therefore proving the identifier String does behave like a type variable, and does not reference the concrete type String.
It would also make debugging more difficult if the compiler just assumed that any identifier not in scope was a type variable. It therefore, makes sense to have to declare it at the beginning of the function definition.

Scala - mapping a list of integers to a method that receives java.lang.Object

Working in Scala-IDE, I have a Java library, in which one of the methods receives java.lang.Object. And I want to map a list of Int values to it. The only solution that works is:
val listOfInts = groupOfObjects.map(_.getNeededInt)
for(int <- listOfInts) libraryObject.libraryMethod(int)
while the following one:
groupOfObjects.map(_.getNeededInt).map(libraryMethod(_)
and even
val listOfInts = groupOfObjects.map(_.getNeededInt)
val result = listOfInts.map(libraryObject.libraryMethod(_))
say
type mismatch; found : Int required: java.lang.Object Note: an
implicit exists from scala.Int => java.lang.Integer, but methods
inherited from Object are rendered ambiguous. This is to avoid a
blanket implicit which would convert any scala.Int to any AnyRef. You
may wish to use a type ascription: x: java.lang.Integer.
and something like
val result = listOfInts.map(libraryObject.libraryMethod(x => x.toInt))
or
val result = listOfInts.map(libraryObject.libraryMethod(_.toInt))
does not work also.
1) Why is it happening? As far as I know, the for and map routines do not differ that much!
2) Also: what means You may wish to use a type ascription: x: java.lang.Integer? How would I do that? I tried designating the type explicitly, like x: Int => x.toInt, but that is too erroneus. So what is the "type ascription"?
UPDATE:
The solution proposed by T.Grottker, adds to it. The error that I am getting with it is this:
missing parameter type for expanded function ((x$3) => x$3.asInstanceOf[java.lang.Object])
missing parameter type for expanded function ((x$3) => x$3.asInstanceOf{#null#}[java.lang.Object]{#null#}) {#null#}
and I'm like, OMG, it just grows! Who can explain what all these <null> things mean here? I just want to know the truth. (NOTE: I had to replace <> brakets with # because the SO engine cut out the whole thing then, so use your imagination to replace them back).
The type mismatch tells you exactly the problem: you can convert to java.lang.Integer but not to java.lang.Object. So tell it you want to ask for an Integer somewhere along the way. For example:
groupOfObjects.map(_.getNeededInt: java.lang.Integer).map(libraryObject.libraryMethod(_))
(The notation value: Type--when used outside of the declaration of a val or var or parameter method--means to view value as that type, if possible; value either needs to be a subclass of Type, or there needs to be an implicit conversion that can convert value into something of the appropriate type.)

What is the point of multiple parameter clauses in function definitions in Scala?

I'm trying to understand the point of this language feature of multiple parameter clauses and why you would use it.
Eg, what's the difference between these two functions really?
class WTF {
def TwoParamClauses(x : Int)(y: Int) = x + y
def OneParamClause(x: Int, y : Int) = x + y
}
>> val underTest = new WTF
>> underTest.TwoParamClauses(1)(1) // result is '2'
>> underTest.OneParamClause(1,1) // result is '2'
There's something on this in the Scala specification at point 4.6. See if that makes any sense to you.
NB: the spec calls these 'parameter clauses', but I think some people may also call them 'parameter lists'.
Here are three practical uses of multiple parameter lists,
To aid type inference. This is especially useful when using higher order methods. Below, the type parameter A of g2 is inferred from the first parameter x, so the function arguments in the second parameter f can be elided,
def g1[A](x: A, f: A => A) = f(x)
g1(2, x => x) // error: missing parameter type for argument x
def g2[A](x: A)(f: A => A) = f(x)
g2(2) {x => x} // type is inferred; also, a nice syntax
For implicit parameters. Only the last parameter list can be marked implicit, and a single parameter list cannot mix implicit and non-implicit parameters. The definition of g3 below requires two parameter lists,
// analogous to a context bound: g3[A : Ordering](x: A)
def g3[A](x: A)(implicit ev: Ordering[A]) {}
To set default values based on previous parameters,
def g4(x: Int, y: Int = 2*x) {} // error: not found value x
def g5(x: Int)(y: Int = 2*x) {} // OK
TwoParamClause involves two method invocations while the OneParamClause invokes the function method only once. I think the term you are looking for is currying. Among the many use cases, it helps you to breakdown the computation into small steps. This answer may convince you of usefulness of currying.
There is a difference between both versions concerning type inference. Consider
def f[A](a:A, aa:A) = null
f("x",1)
//Null = null
Here, the type A is bound to Any, which is a super type of String and Int. But:
def g[A](a:A)(aa:A) = null
g("x")(1)
error: type mismatch;
found : Int(1)
required: java.lang.String
g("x")(1)
^
As you see, the type checker only considers the first argument list, so A gets bound to String, so the Int value for aa in the second argument list is a type error.
Multiple parameter lists can help scala type inference for more details see: Making the most of Scala's (extremely limited) type inference
Type information does not flow from left to right within an argument list, only from left to right across argument lists. So, even though Scala knows the types of the first two arguments ... that information does not flow to our anonymous function.
...
Now that our binary function is in a separate argument list, any type information from the previous argument lists is used to fill in the types for our function ... therefore we don't need to annotate our lambda's parameters.
There are some cases where this distinction matters:
Multiple parameter lists allow you to have things like TwoParamClauses(2); which is automatically-generated function of type Int => Int which adds 2 to its argument. Of course you can define the same thing yourself using OneParamClause as well, but it will take more keystrokes
If you have a function with implicit parameters which also has explicit parameters, implicit parameters must be all in their own parameter clause (this may seem as an arbitrary restriction but is actually quite sensible)
Other than that, I think, the difference is stylistic.