Is 'yield' in Scala equivalent to a display function?

I am starting to learn the Scala programming language. I understand some FP languages โ€‹โ€‹like Erlang and Haskell, and I doubt the meaning of the for / yield expression, for example:

for (arg <- args) yield arg.length 

This will collect an array with the length of any input argument. From what I understood, this looks like a map function in normal FP programming:

 map (\a -> a * 2) [1, 2, 3] (in Haskell) 

I know that the Scala library contains the scala.collection.map method, so I would like to know: is there any difference or restriction in using any style, or are they exactly the same?

+6
source share
3 answers

for ... yield understanding in Scala is converted by the compiler to calls to the map , flatMap and withFilter . for without yield will be translated into a call to the foreach method. Here you can find some examples and more detailed information:

http://tataryn.net/2011/10/whats-in-a-scala-for-comprehension/

and here

http://adamwojtuniak.wordpress.com/2010/09/24/scala-for-comprehensions/

+14
source

Scala for / yield expressions are completely equivalent to the list / monad views in Haskell and have exactly the same capabilities if you stick to the same type for the for expression. (I do not know about Erlang.)

In particular, your example accurately translates to [length arg | arg <- args] [length arg | arg <- args] , translating a call to the Scala xf method into a Haskell fx function application.

+6
source

The summary for the lesson comes down to maps - it is in the Program in the Scala book.

+3
source

Source: https://habr.com/ru/post/913371/


All Articles