Scala Functional Programming in Scala 3 — Questions and Answers
Question 1: What is a monad in Scala functional programming?
- A design pattern for concurrency
- A type that supports `flatMap` and `unit` operations following specific laws (Correct answer)
- A type of recursive data structure
- A debugging utility
Correct answer: A type that supports `flatMap` and `unit` operations following specific laws
A monad is an abstraction that wraps a value and supports `flatMap` (chain) and `unit` (wrap) while satisfying identity and associativity laws.
Question 2: Which annotation verifies that a recursive Scala function is tail-recursive?
- @recursive
- @tailrec (Correct answer)
- @optimize
- @stackSafe
Correct answer: @tailrec
The `@tailrec` annotation from `scala.annotation.tailrec` causes the compiler to verify and optimize tail-recursive functions.
Question 3: What is currying in Scala?
- Converting multiple argument lists into a single argument function
- Transforming a function taking multiple parameters into a chain of single-parameter functions (Correct answer)
- Partial application of a type class
- Memoizing function results
Correct answer: Transforming a function taking multiple parameters into a chain of single-parameter functions
Currying transforms a function `f(a, b)` into `f(a)(b)`, enabling partial application and function composition.
Question 4: What does `zip` do when called on two Scala Lists?
- Concatenates the lists
- Creates tuples pairing elements at corresponding positions (Correct answer)
- Interleaves elements alternately
- Computes the set intersection
Correct answer: Creates tuples pairing elements at corresponding positions
`zip` pairs elements from two collections by index into tuples, stopping at the shorter collection's length.
Question 5: What is partial function application in Scala?
- Applying a function to some but not all arguments to create a new function (Correct answer)
- A function that returns Option
- Defining only part of a function body
- Using _ for unused parameters
Correct answer: Applying a function to some but not all arguments to create a new function
Partial application fixes some arguments of a function, returning a new function that takes the remaining arguments.
Question 6: Which Scala collection operation returns the first element matching a predicate?
- findFirst
- head
- find (Correct answer)
- first
Correct answer: find
The `find` method on Scala collections returns `Option[A]`, yielding `Some(element)` for the first match or `None` if none exists.
What is a monad in Scala functional programming?