Functional Programming in Scala: Capstone Certificate Practice Exam, Exams of Technology

A practice exam for the functional programming in scala capstone certificate. It includes multiple-choice questions covering key concepts such as pure functions, immutability, tail recursion, higher-order functions, sum types, pattern matching, options, and futures. Each question is followed by the correct answer and a detailed explanation. This exam is designed to test and reinforce understanding of functional programming principles in scala, making it a valuable resource for students and professionals preparing for certification or seeking to deepen their knowledge of the subject. The questions cover a wide range of topics, from basic syntax and data structures to more advanced concepts like monads and parallel collections. The explanations provide clear and concise insights into the underlying principles, helping learners grasp the nuances of functional programming in scala. This practice exam is an excellent tool for self-assessment and preparation.

Typology: Exams

2025/2026

Available from 12/20/2025

shilpi-jain-1
shilpi-jain-1 🇮🇳

4.2

(5)

29K documents

1 / 96

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Functional Programming in Scala Capstone
Certificate Practice Exam
**Question 1.** Which of the following best describes a pure function in Scala?
A) It may modify a mutable variable declared outside its scope.
B) It always returns the same result given the same arguments and has no side effects.
C) It throws an exception for any input.
D) It relies on random number generation.
Answer: B
Explanation: A pure function is deterministic (same output for same inputs) and does not cause
side effects such as mutating external state or performing I/O.
**Question 2.** In Scala, which keyword enforces immutability of a reference?
A) var
B) def
C) val
D) lazy
Answer: C
Explanation: `val` defines a value that cannot be reassigned after its initial definition, making the
reference immutable.
**Question 3.** Which annotation tells the compiler to verify that a recursive method is
tailrecursive?
A) @tailcall
B) @tailrec
C) @recursive
D) @optimise
Answer: B
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60

Partial preview of the text

Download Functional Programming in Scala: Capstone Certificate Practice Exam and more Exams Technology in PDF only on Docsity!

Certificate Practice Exam

Question 1. Which of the following best describes a pure function in Scala? A) It may modify a mutable variable declared outside its scope. B) It always returns the same result given the same arguments and has no side effects. C) It throws an exception for any input. D) It relies on random number generation. Answer: B Explanation: A pure function is deterministic (same output for same inputs) and does not cause side effects such as mutating external state or performing I/O. Question 2. In Scala, which keyword enforces immutability of a reference? A) var B) def C) val D) lazy Answer: C Explanation: val defines a value that cannot be reassigned after its initial definition, making the reference immutable. Question 3. Which annotation tells the compiler to verify that a recursive method is tail‑recursive? A) @tailcall B) @tailrec C) @recursive D) @optimise Answer: B

Certificate Practice Exam

Explanation: @tailrec forces the compiler to check that the method is tail‑recursive; if not, compilation fails. Question 4. What is the result of applying List(1,2,3).map(_ * 2)? A) List(1,2,3) B) List(2,4,6) C) List(0,1,2) D) List(3,6,9) Answer: B Explanation: map applies the function _ * 2 to each element, doubling them. Question 5. Which higher‑order function can be used to flatten a List[List[Int]] into a single List[Int] while also applying a transformation? A) map B) filter C) flatMap D) foldLeft Answer: C Explanation: flatMap maps each inner list to a collection and then concatenates the results, achieving both mapping and flattening. Question 6. Given val f: Int => Int = _ + 1 and val g: Int => Int = _ * 3, what does f compose g compute for input 2? A) (2 + 1) * 3 = 9 B) (2 * 3) + 1 = 7 C) 2 + 1 + 3 = 6

Certificate Practice Exam

B) object Person { def apply(name: String, age: Int): Person = new Person(name, age) } C) object Person { def unapply(name: String, age: Int): Person = Person(name, age) } D) object Person { def unapply(p: Person): (String, Int) = (p.name, p.age) } Answer: A Explanation: An extractor must define unapply returning an Option of the components to be extracted. Question 10. What does Option[Int] represent in Scala? A) A collection that may contain zero or more integers. B) A value that is either Some[Int] or None. C) An integer that can be null. D) A mutable container for integers. Answer: B Explanation: Option encodes the presence (Some) or absence (None) of a value, avoiding nulls. Question 11. Which method on Option will return the contained value or a default if the option is None? A) getOrElse B) map C) flatMap D) filter Answer: A Explanation: getOrElse supplies a fallback value when the option is empty. Question 12. When using Either[String, Int], which side conventionally holds an error?

Certificate Practice Exam

A) Left B) Right C) Both sides can hold errors. D) Neither side; errors are thrown. Answer: A Explanation: By convention, Left represents failure (error) and Right represents success. Question 13. Which of the following converts a Try[Int] to an Option[Int] safely? A) tryOption.toOption B) tryOption.get C) tryOption.orNull D) tryOption.fold(Some(_), None) Answer: A Explanation: Try provides toOption that yields Some(value) on Success and None on Failure. Question 14. How can an implicit parameter be defined in a method signature? A) def foo()(implicit ec: ExecutionContext) B) def foo()(ec: ExecutionContext) C) def foo()(implicit ec) D) def foo(implicit ec: ExecutionContext)() Answer: A Explanation: The syntax def foo()(implicit ec: ExecutionContext) declares an implicit parameter list.

Certificate Practice Exam

Explanation: The syntax with two generators (<-) translates to a flatMap followed by a map. Question 18. What is the effect of declaring lazy val data = heavyComputation()? A) heavyComputation runs immediately at object construction. B) heavyComputation runs each time data is accessed. C) heavyComputation runs once, the first time data is accessed, and its result is cached. D) lazy val is illegal; only def can be lazy. Answer: C Explanation: lazy val defers evaluation until first use and memoizes the result. Question 19. Which Scala collection represents a potentially infinite, lazily evaluated sequence? A) List B) Vector C) Stream (Scala 2) / LazyList (Scala 2.13+) D) Array Answer: C Explanation: LazyList (formerly Stream) computes elements on demand and can represent infinite sequences. Question 20. In functional reactive programming, a signal typically models: A) A mutable variable updated imperatively. B) A time‑varying value that can be observed and transformed declaratively. C) A static configuration parameter. D) A low‑level socket connection. Answer: B

Certificate Practice Exam

Explanation: Signals (or observables) represent values that change over time and can be composed functionally. Question 21. Which of the following statements about parallel collections in Scala is true? A) Calling .par automatically makes the collection thread‑safe for mutations. B) Parallel collections guarantee deterministic ordering of results regardless of the operation. C) Operations on a parallel collection must be associative to produce correct results for reductions. D) Parallel collections cannot be converted back to sequential collections. Answer: C Explanation: For reductions like reduce, the operation must be associative; otherwise parallel results may be incorrect. Question 22. Which method converts a regular Seq into a parallel collection? A) toParallel B) parallelize C) par D) asParallel Answer: C Explanation: The par method returns a parallel version of the collection. Question 23. When using Future, which of the following is required to execute the asynchronous computation? A) An implicit ExecutionContext B) A Thread object C) A Promise object

Certificate Practice Exam

C) map D) join Answer: C Explanation: map applies a function to each element locally; it does not require data movement across partitions. Question 27. Which Spark action triggers the execution of the lineage graph and returns the result to the driver? A) map B) filter C) collect D) persist Answer: C Explanation: collect materializes the RDD and brings all elements to the driver, forcing computation. Question 28. Which of the following RDD transformations results in a shuffle? A) filter B) mapPartitions C) distinct D) sample Answer: C Explanation: distinct requires moving records so that duplicates can be identified across partitions, causing a shuffle. Question 29. When reading a large CSV file into an RDD, which method should be used to ensure that each line is parsed into a case class Record without causing serialization issues?

Certificate Practice Exam

A) rdd.map(line => line.split(",")) B) rdd.mapPartitions(iter => iter.map(parseLine)) where parseLine is a top‑level function C) rdd.foreach(parseLine) D) rdd.collect().map(parseLine) Answer: B Explanation: Using a top‑level (or object) function inside mapPartitions avoids capturing outer mutable state, ensuring the function is serializable. Question 30. Which of the following is a correct way to compute the average temperature per station using Spark RDDs? A) rdd.map(r => (r.station, r.temp)).reduceByKey(_ + _) B) rdd.map(r => (r.station, (r.temp, 1))).reduceByKey{ case ((sum1, cnt1), (sum2, cnt2)) => (sum1+sum2, cnt1+cnt2) }.mapValues{ case (sum, cnt) => sum / cnt } C) rdd.groupBy(r => r.station).mapValues(_.map(_.temp).sum) D) rdd.filter(_.temp > 0).meanBy(_.station) Answer: B Explanation: The pattern (temp,1) accumulates sum and count, then division yields the average. Option A lacks count, C uses groupBy which can cause memory pressure, D is not a real Spark API. Question 31. Which of the following best describes the purpose of a type class in Scala? A) To provide inheritance hierarchies for data models. B) To allow ad‑hoc polymorphism by defining behavior that can be injected via implicits. C) To enforce compile‑time singleton objects. D) To replace the need for generic types. Answer: B

Certificate Practice Exam

D) Stream[Color] Answer: B Explanation: Vector provides efficient random access and is immutable, making it appropriate for a fixed‑size 2‑D grid. Question 35. Which Spark transformation should be used to assign each temperature reading to a grid cell based on its coordinates? A) map B) flatMap C) filter D) cartesian Answer: A Explanation: A simple map can compute the cell key from coordinates and emit (cellKey, reading) pairs. Question 36. Which of the following is a correct way to make a custom function serializable for use in Spark transformations? A) Extend java.io.Serializable in the function’s class/object. B) Declare the function inside a def that captures no outer mutable state. C) Use a lambda that references only local immutable values. D) All of the above. Answer: D Explanation: All listed approaches ensure the function can be shipped to executors without serialization problems. Question 37. In a for‑comprehension over a Future[Option[Int]], which sequence of methods is applied behind the scenes?

Certificate Practice Exam

A) map then flatten B) flatMap then map C) map then flatMap D) flatten then map Answer: C Explanation: for { o <- futureOpt; v <- o } yield v translates to futureOpt.map(_.flatMap(v => Future.successful(v))), effectively map followed by flatMap. Question 38. Which of the following is true about the foldLeft method on a List? A) It processes elements from right to left. B) It requires the accumulator function to be associative. C) It can be used to implement tail‑recursive traversals. D) It returns an Option of the result. Answer: C Explanation: foldLeft traverses the list left‑to‑right, threading an accumulator; its implementation is tail‑recursive. Question 39. Which of the following statements about lazy val and thread safety is correct? A) lazy val is not thread‑safe; concurrent accesses may compute the value multiple times. B) lazy val is thread‑safe; the JVM guarantees that the initializer runs at most once. C) lazy val is only safe when used inside objects, not classes. D) lazy val must be combined with synchronized to be safe. Answer: B Explanation: The Scala compiler generates synchronization code ensuring a lazy val is initialized exactly once, even under concurrent access.

Certificate Practice Exam

Answer: A Explanation: MEMORY_ONLY keeps the RDD in RAM without serialization. Question 43. Which of the following is an example of a product type in Scala? A) sealed trait Shape with subclasses Circle and Square B) case class Point(x: Double, y: Double) C) Either[String, Int] D) Option[Boolean] Answer: B Explanation: A product type combines multiple values into one (tuple or case class); Point aggregates x and y. Question 44. Which Scala feature enables the creation of a domain‑specific language (DSL) for building pipelines? A) Implicit conversions and classes B) While loops C) Java interop D) Reflection Answer: A Explanation: Implicit classes and conversions allow extending existing types with new methods, facilitating DSL creation. Question 45. Which of the following statements about foldRight on a List is correct? A) It is tail‑recursive. B) It processes elements from left to right. C) It can be used to build a list in reverse order efficiently.

Certificate Practice Exam

D) It requires the accumulator function to be evaluated lazily for infinite lists. Answer: D Explanation: foldRight is not tail‑recursive; for infinite lists the accumulator must be lazy to avoid non‑termination. Question 46. Which of the following is the most appropriate way to model a finite state machine in Scala using ADTs? A) Use mutable variables to store the current state. B) Define a sealed trait State with case objects for each state and a transition function returning a new State. C) Encode states as integers and use pattern matching on raw numbers. D) Use a Java enum. Answer: B Explanation: A sealed trait with case objects provides a type‑safe, immutable representation of states, and a pure transition function yields the next state. Question 47. Which of the following statements about parallel collections is false? A) They automatically use all available cores. B) They provide a tasksupport field to customize the thread pool. C) They guarantee the same order of results as sequential collections for all operations. D) They can be converted back to sequential collections with .seq. Answer: C Explanation: Some operations (e.g., reduce) may produce nondeterministic ordering unless the operation is associative and commutative. Question 48. Which of the following is a correct way to define a type class for converting a value to JSON?

Certificate Practice Exam

Explanation: Laziness defers computation until needed, saving work and enabling constructs like infinite streams. Question 51. Which of the following expressions correctly creates a tail‑recursive factorial function? A) def fact(n: Int): Int = if (n == 0) 1 else n * fact(n-1) B) @tailrec def fact(n: Int, acc: Int = 1): Int = if (n == 0) acc else fact(n-1, n * acc) C) def fact(n: Int) = List.iterate(1)(_ + 1).take(n).product D) def fact(n: Int) = (1 to n).foldLeft(1)(_ * _) Answer: B Explanation: The function has the accumulator as the last operation (fact(n-1, n * acc)) and is annotated with @tailrec. Question 52. Which of the following is the correct way to compose two functions f: A => B and g: B => C so that the resulting function has type A => C? A) f andThen g B) g compose f C) Both A and B D) Neither A nor B Answer: C Explanation: f andThen g and g compose f are equivalent; both produce A => C. Question 53. Which of the following statements about Option.map is true? A) It returns None if the original Option is Some. B) It applies the function only when the Option is Some. C) It throws an exception when the Option is None.

Certificate Practice Exam

D) It changes the type of the Option to Try. Answer: B Explanation: map transforms the contained value if present; otherwise it leaves None unchanged. Question 54. Which of the following is a pure way to read a configuration value from a Map[String, String]? A) config("host") (throws if missing) B) config.get("host") returning Option[String] C) config.update("host", "localhost") D) println(config("host")) Answer: B Explanation: get returns an Option without side effects, preserving purity. Question 55. Which of the following is an example of a higher‑order function in the Scala standard library? A) List(1,2,3).size B) List(1,2,3).map(_ + 1) C) val x = 5 D) new java.util.ArrayList[Int]() Answer: B Explanation: map takes a function as a parameter, making it a higher‑order function. Question 56. In the context of the capstone, which of the following best describes the role of signals? A) They are mutable variables used to store intermediate results.