Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

SCALA // Define the integer type as a type alias for convenience type Inte = Int // Define the base trait for the grammar sealed

SCALA

// Define the integer type as a type alias for convenience

type Inte = Int

// Define the base trait for the grammar

sealed trait CFrac

// Define the case classes for the productions

case class OneByNumber(i: Inte) extends CFrac

case class NumPlusContFrac(i: Inte, cfrac: CFrac) extends CFrac

// Define the inductive grammar

object CFrac {

def apply(str: String): CFrac = {

val tokens = str.split(" ").filter(_.nonEmpty).toList

buildCFrac(tokens)

}

def buildCFrac(tokens: List[String]): CFrac = tokens match {

case List(i) => OneByNumber(i.toInt)

case i :: cfrac :: rest => NumPlusContFrac(i.toInt, buildCFrac(cfrac :: rest))

}

}

Using the above code:

Implement a function double_of_cfrac that takes in a continued fraction expressed using the inductive definition above and evaluates the corresponding double precision number.

Restrictions:

You are required to use case pattern matching.

Your function need not be tail recursive.

Forbidden: use of loops, mutable (vars), return statement.

Your program should pass the following tests:

val g1 = NumPlusContFrac(2,NumPlusContFrac(3,OneByNumber(4)))

testWithMessage(double_of_cfrac(g1), 0.43333333, " # 1")

val g2 = OneByNumber(2)

testWithMessage(double_of_cfrac(g2), 0.5, " # 2")

val g3 = NumPlusContFrac(3, NumPlusContFrac(-1, OneByNumber(5)))

testWithMessage(double_of_cfrac(g3), 0.57142857, " # 3")

val g4 = NumPlusContFrac(1, OneByNumber(-2))

testWithMessage(double_of_cfrac(g4), 2.0, " # 4")

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Relational Database Technology

Authors: Suad Alagic

1st Edition

354096276X, 978-3540962762

More Books

Students also viewed these Databases questions

Question

3. Are our bosses always right? If not, what should we do?

Answered: 1 week ago

Question

2. What, according to Sergey, was strange at this meeting?

Answered: 1 week ago