What does this mean: map (1 + ) - scala

I mean, I know what it means: take the list and add 1 to each element in it; that is, it's equivalent to map (1 + _ ). What I don't understand is how Scala knows it's equivalent. What's going on here?
Edit
Daniel points out it's a more general question. For example
def g(f : Int => Int, x : Int) = f(f(x))
g( (1 + ), 2)
res12: Int = 4
Which is cool. Every day I find a new useful thing that Scala can do. I guess what I'm looking for a full description (and ideally a name) of this particular thing.

It goes a bit like this:
map expects a function Int => B (in this case).
1 + doesn't resolve to a function Int => B, so try other things.
1 + can be lifted from a method expecting an Int parameter to a function Int => Int.
Presto.
One uses 1 + _ to solve ambiguity.

Related

Scala - flatMap

I am new to programming and was wondering if anyone can please help me out with this simple problem which is slightly confusing for me.
Code:
(1 to 3).toList.flatMap(i => (1 to i).map(j => i * j))
I don't understand int his part flatMap(i => (1 to i) <-- i is not assigned so what pattern does it get mapped in and why?
Also same thing with (j => i * j) how do we know what j is? there is no value for j.
I tried to figure out what pattern it makes:
1,1,2,1,2,3 <-- don't understand why it creates this pattern?
I hope i am making sense.
Thanks,
i => foo is a lambda syntax, so this is creating a function so here i is the input of that function, it doesn't have a value yet, it will have a value when the function is called. This is similar creating a method like def bar(x: Int): Int = x + 1, what is the value of x? none, it is just a name for the input it will have a value once called.
It may help to understand seeing the more common for syntax:
val result = for {
i <- (1 to 3).toLis
j <- 1 to i
} yield i * j
This syntax, which is just sugar syntax for your previous code, makes it easier to understand how this executes under the hood.
Anyways, this is a pretty basic question.
I would recommend you to take a look at the tour and / or other tutorials / books / courses.
And to rather ask this kind of questions in the gitter channel which is more suited for newcomers.

In which scenario '=' used and '=>' used in scala? [duplicate]

This question already has an answer here:
Can anyone explain how the symbol "=>" is used in Scala
(1 answer)
Closed 4 years ago.
I am new to scala and I confused little bit with = and =>, I don't know in which scenario exactly = used and => used.
#RamanMishra's comment is correct, however I would like to expand it a bit hopping it becomes more clear to you.
a = b means a is now equals to b (in the imperative meaning of the word, which is better understood as assignment).
It is used in many places, including when defining a function\method, for example
def sum(a: Int, b: Int): Int = a + b
The above statement can be readed as:
"We defined a function with name sum which takes two parameters (a & b) both of type Int and returns an Int. And its body\implementation is 'equals' to a + b".
a => b means, there is a function which takes a parameters list a and has a body b, it is used a couple of places, including anonymous functions and higher-order functions.
val anonymous: Int => Int = x => x + 1
The above statement can be readed as:
"We defined a value called anonymous, whose type is a function with one parameter of type Int and a return type Int, which is 'equals' to the 'anonymous' function which takes one parameter x (its type is inferred in by the context, in this type the explicit type signature before) and its body is x + 1"
def higherOrder(x: Int, f: Int => Int): Int = f(x)
The above statement can be readed as:
"There is a function (sum), which takes another function as a parameter (f), the later is a function of type Int to Int".
Edit
As #Aki suggested, the => is also used in pattern matching to separate the cases and the block of code to execute for each one.
def fact(n: Long): Long = n match {
case 0L => 1L
case n => n * fact(n - 1)
}
"This is somewhat similar to a parameter list => function body, as the above examples".
PS: This is a 101 Scala question, SO is not the best place for such questions, because there is probably enough resources on the internet - like this cheatsheet, or better places to ask - like the scala gitter channel.

Scala strange error when using foldRight with operator syntax

1 to 5 foldRight (0)(x:Int, y:Int => x+y)
I am trying to add all the values from right to left with 0 as the initial parameter. I get the following error
Int(0) does not take parameters
Can anyone explain to me what this error even means?
Thanks.
It's just the parser getting "confused", so it's trying to apply (x: Int, y: Int ...) as argument of (0).
Specifically, what you're using is a scala syntactic feature that allows to use
a.f(b)
as
a f b
This works with any method that has a single parameter. However when your method has multiple parameter lists (like foldRight), you have to use extra care.
This is what the parser sees
1 to 5 foldRight (0)(x: Int, y: Int => x + y)
|__a__| |___f___| |____________b_____________|
So when evaluating b, it treats 0 as a function with (x: Int, ...) as an argument.
Clearly this can't work, because "Int(0) does not take parameters".
Instead, you can use
(1 to 5).foldRight(0)((x,y) => x + y)
or even
(1 to 5).foldRight(0)(_ + _)
There are two things wrong with your code. The first is that you need to use brackets around 1 to 5, the second is the syntax of your anonymous function. You need brackets around the parameters there.
(1 to 5).foldRight(0)((x,y) => x + y)

Currying in scala

w.r.t Currying in scala, partly I understood below sample code.
def product1(f:Int => Int )(a:Int, b:Int):Int = {
println()
if(a > b ) 1
else
f(a) * product1(f)(a+1, b)
}
product(x => x * x) (3, 4)
Out of it., I am bit confused with
product1(f)
in
product1(f)(a+1, b)
Just need explanation, what goes on here.... :( and how to pronounce verbally while explaining...
Thanks in advance..
product1 has two parameter lists. product1(f) is the application of f which is a function of kind Int => Int. If you were only to call product1(f) like so:
product1(f)
without the second parameter list, you'd get a so-called partially-applied function, i.e. a function which doesn't have all of its parameters bound (you'd still need to provide it with a and b)
Look at the parameter declaration:
f:Int => Int
f is a function that maps an Int to an Int -- it takes an Int as an argument and returns an Int. An example is given:
x => x * x
returns the square of its argument.
product1(x => x * x) (3, 4)
returns the product of f(3) .. f(4) = 3*3 * 4*4
BTW, this isn't really an example of currying, since all the arguments are given. Currying would be something like
val prodSquare = product1(x => x * x)
Then,
prodSquare(1, 5)
yields 1*1 * 2*2 * 3*3 * 4*4 * 5*5
For most idiomatic purposes I've seen, you may as well think of your function as having just one parameter list. Multiple parameter lists are used mostly for type inference purposes in generic functions, since type inference is done one parameter list at a time, rather than using Hindley-Milner/Algorithm W to infer the type of everything at once. Some other language features work on individual parameter lists, such as implicit parameters and implicit use of braces in place of parentheses for single-parameter parameter lists, etc.
Functions with multiple parameter lists are called in a similar way to a curried functions from a syntactic perspective, but by default, the intermediate functions aren't created. In fully curried style, each function takes only at most one argument and returns one result (which might happen to be another function, which expects on argument, and so forth). Technically, currying the function would be:
def product2(f: Int => Int): Int => Int => Int = {
a: Int => {
b: Int => {
if(a > b ) 1
else f(a) * product2(f)(a+1)(b)
}
}
}
For completeness, you can treat a function with multiple parameter lists as a curried function by using an underscore after a complete parameter list. In your original example, you'd do product1(f)_, which would return a function of type (Int, Int) => Int.
In researching this question, I came upon another SO question worth checking out to understand this aspect of the language better.

Scala : why can't I filter my Int List properly with placeholder ? e.g : myList.filter(_:Int => _ % 5 == 0)

I have a little issue related to placeholder syntax in Scala.
So I have a simple List of numbers :
myList = List(13, 24, 10, 35)
first, I tried to filter this list like this
myList.filter(_ => (_ % 5) == 0)
and the compiler complains since it can not infer the parameter type :
error: missing parameter type for expanded function ((x$2) => x$2.$percent(5))
okay, no problem : I added a type for the parameter
myList.filter(_:Int => _ % 5 == 0)
now the compiler gives me this :
identifier expected but integer literal found.
someNumbers.filter(_:Int => _ % 5 == 0)
^
do you guys know why I have this weird error ? I really don't get it ...
thanks in advance,
You have no idea, but this:
identifier expected but integer literal found.
someNumbers.filter(_:Int => _ % 5 == 0)
^
is an awesome error! Well, not in the sense people would like it, but you managed to almost write something syntactically correct and utterly different from what you intended. First, let's look at rewriting that is valid code:
someNumbers.map(_: Int => _ <:< Any)
Now, you see that there are only two differences from it to what you wrote (up to the error position): % replaced with <:, and 5 replaced with Any (as the compiler wanted -- an identifier instead of a number).
You can compile and run the code above, and it will return something, so let's try to break it down. First, consider the two statements below:
someNumbers.map(_ + 1)
someNumber.map(_) // does not compile
They each mean something slightly different, and can be rewritten like this:
someNumbers.map(x => x + 1)
x => someNumbers.map(x)
The first one compiles because, at the time the x parameter is declared, the compiler knows what type is expected. The second one does not compile because, at the time the compiler sees x, it has no idea how it is going to be used. Granted that's only because the compiler has rewritten the code, but that's how it goes.
The important thing here is that, when you added : Int, the compiler started trying to compile what you wrote the second way.
The thing you intended to write is not valid code. For example:
someNumbers.map(x => x + 1) // valid code
someNumbers.map((x: Int) => x + 1) // valid code
someNumbers.map(x : Int => x + 1) // "invalid" code
To be more precise, the third example is "invalid" because the compiler doesn't know where the type ends! To understand why, look at this statement:
val f: Int => Int = x => x
Here we have => appearing twice, but each time with a different meaning! The first case, Int => Int, is syntactic sugar for Function1[Int, Int]. In other words, => in Int => Int is part of the type.
In the second case, x => x (roughly) stands for new Function1[Int,Int] { def apply(x: Int) = x }. The => in this code indicates the presence of an anonymous function, and separates its parameter from its body.
Now we can understand how the compiler interpreted someNumbers.filter(_: Int => _ % 5 == 0). Like this:
someNumbers.filter(_: Int => _ % 5 == 0) // gets rewritten as
(x: Int => _ % 5 == 0) => someNumbers.filter(x)
Meaning that Int => _ % 5 == 0 was assumed to be the type. We already saw why => doesn't stop it, but the error only happened on 5! What's going on between here and there?
First, I'll get back to my compilable example. It makes use of a Scala construct that isn't very well understood, and not often seen either: the infix type notation. That example can be rewritten like below:
someNumbers.map(_: Int => _ <:< Any)
someNumbers.map(_: Int => <:<[_, Any])
In other words, just like 2 * 2 stands for 2.*(2), Int Map String stands for Map[Int, String]. So that explains why the compiler did not stop at % -- it thought it stood for a type -- but it still leaves us with _.
At this point, however, the meaning of _, particularly in the rewritten form, shouldn't look mysterious: it is an existential type! More specifically, it is the wildcard existential type. The whole thing can be rewritten like this:
(x: Function1[Int,<:<[t, Any] forSome { type t }]) => someNumbers.map(x)
Or, without any syntactic sugar (but being slightly different in implementation*):
new Function1[Function1[Int, <:<[t, Any] forSome { type t }], List[<:<[q, Any] forSome { type q }]] {
def apply(x) = someNumbers.map(x)
}
Now, don't you agree this could hardly be farther from what you wanted to write? :-)
(*) Actually, I think t and q are the same in the original, but I haven't figured any way to write it out without syntactic sugar.
You meant this:
val myList = List(13, 24, 10, 35)
myList.filter(x => (x % 5) == 0)
The placeholder _ in something like myList.map(_ + 5) is shorthand for making a function, in this case myList.map(x => x + 5). So myList.map(_ => _ + 5) because it's sort of saying "map each item in myList to the sum of a function x => x and 5".
The other use of placeholders in something like this is to ignore the parameter. So myList.map(_ => 1) means "ignore the item and just map everything to 5". In your case, you need the item to decide whether to filter it, so having _ => doesn't make sense.
The expression myList.filter(x => (x % 5) == 0) means "for each x in myList, keep it if (x % 5) == 0".
What about:
myList.filter(_ % 5 == 0)