Question
SCALA sealed trait CFrac case class OneByNumber(num: Int) extends CFrac case class NumPlusContFrac(num: Int, contFrac: CFrac) extends CFrac case class Frac(num: Int, contFrac: CFrac) extends
SCALA
sealed trait CFrac case class OneByNumber(num: Int) extends CFrac case class NumPlusContFrac(num: Int, contFrac: CFrac) extends CFrac case class Frac(num: Int, contFrac: CFrac) extends CFrac
USING ABOVE, ENSURE THE FOLLOWING PASSES ALL TESTS TOO:
Write a function cfrac_of_list that given a list of integers lst of the form List(a0, a1, ..., an), converts it into the continued fraction of depth given by the numbers a0, .., an in the list. Function takes in a single argument whose type must be List[Int]. Return type of your function must be CFrac. If your input is empty your code must throw an IllegalArgumentException.
Example 1:
Input: List(5)
Function returns: OneByNumber(5)
Example 2:
Input: List(2, 3, 4)
Function returns: NumPlusContFrac(2,NumPlusContFrac(3,OneByNumber(4)))
Restrictions:
No loops, var or return.
You can use pattern matching over Scala Lists and any list API functions of your choice.
Your code must throw an IllegalArgumentException if the list is empty.
Your program should pass the following tests:
val g0 = OneByNumber(5)
testWithMessage(cfrac_of_list(List(5)), g0, "Test # 1")
val g1 = NumPlusContFrac(1,NumPlusContFrac(2,OneByNumber(3)))
testWithMessage(cfrac_of_list(List(1,2,3)), g1, "Test # 2")
try {
println("Calling your function cfrac_of_list on empty list.")
val g = cfrac_of_list(Nil);
assert(false, "No IllegalArgumentException thrown on empty list")
} catch {
case e:IllegalArgumentException => {
println("IllegalArgumentException caught: Expected behavior seen!")
}
case e: Exception => {println(s"Wrong type of exception thrown-- $e")}
}
val g3 = NumPlusContFrac(1,
NumPlusContFrac(1,
NumPlusContFrac(1,
NumPlusContFrac(1,
NumPlusContFrac(1,OneByNumber(1))))))
testWithMessage(cfrac_of_list(List(1,1,1,1,1,1)), g3, "Test # 3")
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started