03: Q13 – Q18 Scala FP combinators interview questions & answers

Q13. What are the different approaches in Scala to solve the following task?

Given numbers 1 to 6, and you need to extract out the odd numbers and double them, and finally print the result.

Java functional programming focusing on transforming data

Java functional programming focusing on transforming data

A13. There are 3 ways to solve the problem.

1) Loops (e.g. for, while, do-while)
2) Recursion
3) Combinators (e.g. map, foreach, filter, flatMap, foldLeft, etc)

Loop

Recursion

:: means “Common method or object”. “::” in this expression is the method of the class List.

tail method returns a list consisting of all elements except the first.

x represents the “head”, which is the first element.

Nil represents an empty list.

x :: tail means x is the head (i.e. first element of the list), and tail is “all elements except the first”.

Functional Combinators

Some of the functional combinators in Scala are like “map“, which applies the supplied function to each element and return the result to a new list. The “foreach” functional combinator does the same things the “map”, but does not return a value. filter removes any element that returns false to the supplied predicate (e.g. x % 2 != 0). There are many other functional combinators like flatten, foldLeft, foldRight, zip, find, partition, dropWhile, etc.

Q14. Which approach among loops, iteration, and higher-order combinators will you favor in which scenario?
A14. As a general rule of thumb, favor “higher-order combinators” over the other two. Looping should only be considered in performance critical sections, and recursion should be considered in some edge cases where combinators cannot be used.

Combinators are not only much easier to read, but also promotes shorter code and fewer mistakes. Combinators allow you to combine small functions into big functions.

Q15. What will be the output of the following code snippet?

A15. The “flatMap” flattens the list of lists to a single list.

Q16. Can the following code snippet be re written with the “foldLeft” combinator?

A16. Yes. The above code doubles each number in the “map” function and then “reduce” all the numbers i.e. (6, 8, 10) by adding each number to the next number:

Pass 1: 14, 10
Pass 2: 24

Using “foldLeft

It starts with 0 as the initial result and then sums the result with the next doubled number.

Pass 1: 0 + 6
Pass 2: 6 + 8
Pass 3: 14 + 10

Q17. How will you go about combining two functions?
A17. You can use the functional combinators like “combine” and “andThen“. Here is an example that is used with a “Future” object, which is used for asynchronous (i.e. non blocking) processing.

Output

Q18. How will you split the following list into odd and even numbers>

A18. You can use the “partition” function.


800+ Java Interview Q&As Menu

Top