Scala Functional Programming Principles Practice Exam, Exams of Technology

A practice exam for functional programming principles in scala. It includes multiple-choice questions covering topics such as immutable bindings, pure functions, evaluation strategies, tail recursion, higher-order functions, currying, traits, and immutable collections. Each question is followed by a detailed explanation of the correct answer, making it a valuable resource for students and professionals preparing for certification or seeking to deepen their understanding of functional programming concepts in scala. The exam covers key concepts and best practices, offering insights into referential transparency, pattern matching, and collection manipulation.

Typology: Exams

2025/2026

Available from 12/20/2025

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

4.2

(5)

29K documents

1 / 90

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Functional Programming Principles in Scala Certificate
Practice Exam
**Question 1. Which Scala construct introduces an immutable binding?**
A) var
B) val
C) def
D) lazy val
Answer: B
Explanation: `val` creates a readonly reference; its value cannot be reassigned, embodying
immutability.
**Question 2. In functional programming, a pure function must**
A) Modify a global variable
B) Depend on mutable state
C) Produce the same output for the same input without side effects
D) Use recursion exclusively
Answer: C
Explanation: Purity means referential transparency—identical inputs always yield identical
outputs and no observable side effects.
**Question 3. Which evaluation strategy evaluates the argument only when it is actually used
inside the function?**
A) Callbyvalue
B) Callbyreference
C) Callbyname
D) Callbyneed
Answer: C
Explanation: Callbyname delays evaluation of the argument until each occurrence in the
function body is accessed.
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

Partial preview of the text

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

Practice Exam

Question 1. Which Scala construct introduces an immutable binding? A) var B) val C) def D) lazy val Answer: B Explanation: val creates a read‑only reference; its value cannot be reassigned, embodying immutability. Question 2. In functional programming, a pure function must A) Modify a global variable B) Depend on mutable state C) Produce the same output for the same input without side effects D) Use recursion exclusively Answer: C Explanation: Purity means referential transparency—identical inputs always yield identical outputs and no observable side effects. Question 3. Which evaluation strategy evaluates the argument only when it is actually used inside the function? A) Call‑by‑value B) Call‑by‑reference C) Call‑by‑name D) Call‑by‑need Answer: C Explanation: Call‑by‑name delays evaluation of the argument until each occurrence in the function body is accessed.

Practice Exam

Question 4. What does the @tailrec annotation guarantee? A) The function is recursive B) The function will be compiled with tail‑call optimization or cause a compilation error C) The function runs in constant time D) The function can be called from Java Answer: B Explanation: @tailrec forces the compiler to verify that the recursion is in tail position; otherwise it reports an error. Question 5. Which of the following is a correct definition of a higher‑order function? A) A function that returns an Int B) A function that takes or returns another function as a parameter C) A function that uses loops D) A function that is defined inside a class Answer: B Explanation: Higher‑order functions treat functions as first‑class values: they can accept them as arguments or return them. Question 6. The expression list.map(_ + 1) is an example of A) Imperative iteration B) Pattern matching C) A higher‑order function using an anonymous function D) Tail recursion Answer: C

Practice Exam

Answer: C Explanation: Any is the root of Scala’s type hierarchy; AnyRef is the root of reference types, but Any is the universal supertype. Question 10. Which of the following statements about immutable collections in Scala is true? A) They can be modified in place B) Operations return new collections leaving the original unchanged C) They are always slower than mutable collections D) They do not support parallel operations Answer: B Explanation: Immutable collections never change; any transformation creates a new collection, preserving the original. Question 11. What does the sealed modifier achieve for a trait or class? A) Prevents inheritance outside the current file B) Allows multiple inheritance C) Makes the type thread‑safe D) Enables runtime reflection Answer: A Explanation: sealed restricts subclassing to the same source file, which helps the compiler exhaustively check pattern matches. Question 12. In pattern matching, the underscore _ is used as A) A wildcard that matches any value without binding it B) A variable that must be previously declared C) A reserved keyword for imports

Practice Exam

D) A syntax error in Scala 2.13+ Answer: A Explanation: _ discards the matched value; it is a placeholder that matches anything. Question 13. The expression case List(x, y, _*) => matches A) Any list with at least two elements B) Exactly three elements C) Only empty lists D) Lists with exactly two elements Answer: A Explanation: x and y bind the first two elements; _ * matches any remaining tail (including empty). Question 14. Which method on a List is defined as def ::[B >: A](elem: B): List[B]? A) append B) prepend (cons) C) map D) flatMap Answer: B Explanation: The :: operator (cons) adds an element to the front of a list, returning a new list. Question 15. Variance annotation +T on a generic class indicates A) Contravariance – the class can accept subtypes of T B) Invariance – the class accepts only exactly T C) Covariance – the class can be substituted with a subclass of T D) No effect on type relationships

Practice Exam

D) All variables are declared with val Answer: B Explanation: Referential transparency allows substitution of an expression with its evaluated result, a core property of pure functional code. Question 19. The Scala for‑comprehension for (x <- xs if x % 2 == 0) yield x * x is syntactic sugar for A) xs.filter(_ % 2 == 0).map(x => x * x) B) xs.map(x => x * x).filter(_ % 2 == 0) C) xs.foreach(x => if (x % 2 == 0) println(x * x)) D) xs.foldLeft(List.empty[Int])((acc, x) => if (x % 2 == 0) acc :+ (x * x) else acc) Answer: A Explanation: The if guard translates to a filter, and yield translates to map. Question 20. Which collection type offers O(log n) lookup and immutable updates? A) List B) Vector C) Set D) Map (immutable) Answer: D Explanation: Immutable Map implementations (e.g., HashMap, TreeMap) provide logarithmic or near‑constant lookup and structural sharing for updates. **Question 21. In Scala, the expression `def factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n

  • 1)suffers from** A) Lack of tail recursion, leading to possible stack overflow for largen` B) Incorrect base case

Practice Exam

C) Use of var instead of val D) Implicit conversion errors Answer: A Explanation: The recursive call is not in tail position because the multiplication occurs after the call, preventing tail‑call optimization. Question 22. Which of the following statements about Option is false? A) Option can be either Some or None B) Option is a monad that supports flatMap C) Option always contains a value D) Option eliminates the need for null checks Answer: C Explanation: Option may be None, representing the absence of a value; thus it does not always contain a value. Question 23. What does the require function do inside a class constructor? A) Throws an IllegalArgumentException if the condition is false B) Logs a warning message C) Performs lazy initialization D) Enforces type constraints at compile time Answer: A Explanation: require validates preconditions; if the predicate is false, it throws an IllegalArgumentException. Question 24. Which of the following is a correct declaration of an immutable case class representing a rational number? A) case class Rational(num: Int, den: Int) { require(den != 0) }

Practice Exam

A) filter followed by map with a partial function B) map followed by flatten C) groupBy then mapValues D) foldLeft with a custom accumulator Answer: A Explanation: collect applies a partial function, keeping only elements where the function is defined, effectively filtering and mapping in one step. Question 28. Which of the following statements about lazy evaluation in Scala is true? A) lazy val is evaluated each time it is accessed B) lazy val is evaluated once, upon first use, and the result is cached C) lazy val cannot be used with immutable collections D) lazy val is only allowed inside objects, not classes Answer: B Explanation: A lazy val is computed the first time it is accessed and the computed value is stored for subsequent accesses. Question 29. In a for‑comprehension, the presence of multiple generators (x <- xs; y <- ys) translates to which combinator? A) map only B) flatMap followed by map C) filter only D) foldLeft Answer: B Explanation: Each additional generator is translated to a flatMap; the final yield becomes a map.

Practice Exam

Question 30. Which of the following is a correct way to define an implicit parameter list for a higher‑order function that requires an Ordering[T]? A) def sort[T](list: List[T])(implicit ord: Ordering[T]) = list.sorted B) def sort[T](list: List[T], ord: Ordering[T]) = list.sorted C) def sort[T](list: List[T]) = implicit ord: Ordering[T] => list.sorted D) def sort[T](implicit list: List[T], ord: Ordering[T]) = list.sorted Answer: A Explanation: The implicit parameter list (implicit ord: Ordering[T]) allows the compiler to supply an appropriate Ordering automatically. Question 31. The expression list.takeWhile(_ < 5) returns A) All elements after the first element that is not less than 5 B) All elements before the first element that is not less than 5 C) Elements equal to 5 only D) The entire list if any element is less than 5 Answer: B Explanation: takeWhile collects elements from the start of the list while the predicate holds; it stops at the first failure. Question 32. Which trait in Scala’s standard library provides the map operation for collections? A) Traversable B) Iterable C) Seq D) GenTraversableOnce Answer: B Explanation: Iterable defines map, flatMap, filter, etc.; concrete collection types mix it in.

Practice Exam

Explanation: list1 ::: list2 returns a new list consisting of all elements of list1 followed by those of list2. Question 36. Which of the following is a correct way to define a generic immutable stack using a sealed trait and case classes? A) sealed trait Stack[+A]; case object Empty extends Stack[Nothing]; case class Node[A](head: A, tail: Stack[A]) extends Stack[A] B) trait Stack[A]; class Empty extends Stack[A]; class Node[A](head: A, tail: Stack[A]) extends Stack[A] C) sealed abstract class Stack[A]; case class Empty() extends Stack[Nothing]; case class Node(head: A, tail: Stack[A]) extends Stack[A] D) object Stack { def apply[A](xs: A*) = xs.toList } Answer: A Explanation: The sealed trait with covariant type +A and case objects/classes provides an ADT representation of an immutable stack. Question 37. In Scala, which of the following expressions will cause a stack overflow for large n? A) def sum(n: Int): Int = if (n == 0) 0 else n + sum(n-1) B) def sum(n: Int): Int = { @tailrec def loop(i: Int, acc: Int): Int = if (i == 0) acc else loop(i-1, acc+i); loop(n,0) } C) List.range(1, n+1).foldLeft(0)(_ + _) D) Iterator.from(1).take(n).sum Answer: A Explanation: The recursive call is not tail‑recursive; each call adds a new stack frame, leading to overflow for large n. Question 38. Which of the following statements about case class copy method is correct?

Practice Exam

A) It creates a shallow copy and allows selective field modification B) It performs a deep copy of all nested objects C) It is only available for mutable classes D) It returns a Tuple containing the original fields Answer: A Explanation: copy creates a new instance with the same values, letting you override any fields while preserving immutability. Question 39. The expression list.filter(_ % 2 == 0).map(_ * 2) can be rewritten using a single A) foldLeft B) collect C) flatMap D) reduceRight Answer: B Explanation: collect with a partial function case x if x % 2 == 0 => x * 2 both filters and maps in one step. Question 40. In Scala, which of the following is a correct way to express a function that takes a variable number of Int arguments and returns their product? A) def product(nums: Int*): Int = nums.foldLeft(1)(_ * _) B) def product(nums: List[Int]): Int = nums.reduce(_ * _) C) val product = (nums: Seq[Int]) => nums.reduce(_ * _) D) def product(nums: Array[Int]): Int = nums.sum Answer: A Explanation: The * syntax defines a repeated parameter (varargs); foldLeft computes the product starting from 1.

Practice Exam

Explanation: Applicatives allow parallel composition of independent computations, applying a function to multiple effectful values. Question 44. In Scala, what does the :: operator associate to the right? A) list1 :: list2 creates a list where list1 is the head of list2 B) elem :: list prepends elem to list C) list :: elem appends elem to list D) It is left‑associative, so a :: b :: c is parsed as (a :: b) :: c Answer: B Explanation: :: is right‑associative; elem :: list yields a new list with elem as head. Question 45. Which of the following is a correct way to define an implicit conversion from Int to a custom wrapper class RichInt? A) implicit def intToRich(i: Int): RichInt = new RichInt(i) B) def implicit intToRich(i: Int): RichInt = new RichInt(i) C) implicit class RichInt(i: Int) { def square = i * i } D) Both A and C are valid Answer: D Explanation: Both a traditional implicit def and an implicit class provide implicit conversions from Int to RichInt. Question 46. What is the result of List(1,2,3).partition(_ % 2 == 0)? A) (List(2), List(1,3)) B) (List(1,3), List(2)) C) (List(1,2,3), List()) D) (List(), List(1,2,3))

Practice Exam

Answer: A Explanation: partition returns a tuple (matches, nonMatches); even numbers satisfy the predicate, giving (List(2), List(1,3)). Question 47. Which of the following statements about Stream (now LazyList) is true? A) Elements are evaluated eagerly when the stream is created B) It provides infinite, lazily evaluated sequences C) It cannot be used with pattern matching D) It is mutable by default Answer: B Explanation: LazyList (formerly Stream) represents a possibly infinite sequence where elements are computed lazily on demand. Question 48. In Scala, the copy method generated by a case class is A) Overridden automatically when a subclass defines its own copy B) Final and cannot be overridden C) Synthetic and only visible via reflection D) Generated as a def with default arguments for each field Answer: D Explanation: The compiler creates def copy(field1: T1 = this.field1, ...) allowing selective field updates. Question 49. Which of the following best explains why immutable data structures are safe to share between threads? A) They are automatically synchronized by the JVM B) Their state cannot change after creation, eliminating race conditions C) They use volatile fields internally

Practice Exam

C) *T

D) No annotation (invariant) Answer: C Explanation: *T is not a Scala variance annotation; only + (covariant) and - (contravariant) are allowed. Question 53. The unapply method in a companion object of a case class is used for A) Constructing instances B) Deconstructing instances during pattern matching C) Serializing the object to JSON D) Overriding equals Answer: B Explanation: unapply extracts components from an object, enabling pattern matching on case class instances. Question 54. Which of the following collections is guaranteed to preserve insertion order? A) Set B) Map (immutable) C) List D) HashSet Answer: C Explanation: List is an ordered sequence; its elements retain the order they were added. Question 55. The expression list.foldRight(Nil: List[Int])(_ :: _) produces A) The original list reversed B) The original list unchanged

Practice Exam

C) A list of list concatenations D) A compilation error Answer: B Explanation: Folding right with :: and Nil reconstructs the list unchanged; foldLeft with the same function would reverse it. Question 56. Which of the following statements about PartialFunction is true? A) It can be applied to any input without checking isDefinedAt B) It is defined only for a subset of its input domain and provides isDefinedAt to test applicability C) It always returns an Option D) It cannot be used with collect Answer: B Explanation: PartialFunction defines apply (which may throw) and isDefinedAt to test whether the function is defined for a given input. Question 57. In Scala, the zipWithIndex method on a collection returns A) A list of pairs (element, index) where index starts at 0 B) A map from elements to their indices C) A tuple of two lists: elements and indices D) The original collection with an additional hidden index field Answer: A Explanation: zipWithIndex pairs each element with its zero‑based position, yielding a collection of tuples. Question 58. Which of the following best describes the purpose of the Monad laws (left identity, right identity, associativity)?