简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM