Midterm Exam Spring '23 v1 (Solutions)
.pdf
keyboard_arrow_up
School
University of California, Los Angeles *
*We aren’t endorsed by this school
Course
131
Subject
Computer Science
Date
Dec 6, 2023
Type
Pages
5
Uploaded by ColonelRockGoldfinch39
CS131 Spring 23 - Midterm #1
version 1 rubric
1. [10 points-2 each] For each of the items below, write a Haskell type signature for the
expression. If the item is a function then use the standard haskell type notation for a function. If
the item is an expression, write the type of the expression (e.g., [Int]). For any answers that use
one or more type variables
where concrete types can't be inferred
, use "t1", "t2", etc. for your
type variable names.
a. foo bar = map (\x -> 2 * x) bar
b. z = \x -> x ++ ["carey"]
c. m = [((\a -> length a < 7) x,take 3 y) |
x <- ["matt","ashwin","siddarth","ruining"],
y <- ["monday","tuesday","wednesday","thursday","friday"]]
d. z = foldl (\x y -> x ++ y)
e. foo bar = []
Answers:
Any option listed below is worth full credit. Answers that fail to use
types t1, t2, etc. but instead use other letters or type names should
get full credit if their answer is valid. An answer is either entirely
correct or entirely wrong.
a.
foo :: Num t1 => [t1] -> [t1]
foo :: [Int] -> [Int]
foo :: [Integer] -> [Integer]
full points if they don’t include the function name (e.g. ‘foo ::’)
full points if they don’t use a generic for instance of the Num class
(e.g. giving full points for ‘Num => [Num] -> [Num]’
b.
z :: [[Char]] -> [[Char]]
z :: [String] -> [String]
c.
m :: [(Bool, [Char])]
m :: [(Bool, String)]
[(Bool, [Char])]
[(Bool, String)]
d.
z :: [t1] -> [[t1]] -> [t1]
z :: Foldable t2 => [t1] -> t2 [t1] -> [t1]
note: the second answer involves type classes, which is out of
scope of the class!
e.
foo :: t1 -> [t2]
2. [5 points] Suppose a language does not support closures. Is it possible for the language to
still support currying and partial function application? If so, how would this work; if not, explain
why not. Note: Limit your answer to five or fewer sentences, and avoid adding superfluous,
incorrect answers as this will result in a point deduction.
Answer:
●
Any answer that hits the following points gets full credit:
Currying requires closures to capture free variables used in the inner
lambda expressions. If there are no closures then we can't create
curried functions or do partial application.
●
If the student just says currying/PA is not possible but does not give
a rationale they get 1 point
●
If the student also includes superfluous answers that are not correct,
take one point off for each incorrect answer that is present.
●
The minimum score for this problem is zero.
3. [16 points-2/2/2/10] In this question, you will be implementing
directed graph
algebraic data
types and algorithms in Haskell. Recall that a graph is composed of nodes that hold values, and
edges which connect nodes to other nodes. In a directed graph, edges are unidirectional, so an
outgoing edge from node A to node B does NOT imply that B also has a direct connection to A.
You may assume that all graphs have at least one node.
a. Show the Haskell definition for an algebraic data type called "Graph" that has a single “Node”
variant. Each Node must have one Integer value, and a list of zero or more adjacent nodes that
can be reached from the current node.
Answer:
Any of the following answers is OK:
data Graph = Node Int [Graph]
data Graph = Node Integer [Graph]
data Graph = Node [Graph] Int
data Graph = Node [Graph] Integer
If the student uses a type variable with a type of Integral that's ok too.
All other answers get a zero.
b. Using your Graph ADT, write down a Haskell expression that represents a graph with two
nodes:
1.
A node with the value 5 with no outgoing edges
2.
A node with the value 42, with an outgoing edge to the previous node
Answer:
The students may use any variable names they like (instead of a and b).
Given these definitions from part a:
data Graph = Node Int [Graph]
data Graph = Node Integer [Graph]
Either of the following options are valid:
a = Node 5 []
– 1 point
b = Node 42 [a]
– 1 point
b = Node 42 [Node 5 []]
– 2 points
Given these definitions from part a:
data Graph = Node [Graph] Int
data Graph = Node [Graph] Integer
Either of the following options are valid:
a = Node [] 5
– 1 point
b = Node [a] 42
– 1 point
b = Node [Node [] 5] 42
– 2 points
c. Carey has designed his own graph ADT, and written a Haskell function that adds a node to
the “front” of an existing graph g that is passed in as a parameter:
add_to_front g = Node 0 [g]
In Haskell, creating new data structures incurs cost. Assuming there are N nodes in the existing
graph
g
, what is the time complexity of Carey's function (i.e., the big-O)? Why?
Answer:
O(1) because only a single new node is being created, and it links to the
original graph.
The existing graph need not be regenerated in any way.
d. Write a function called
sum_of_graph
that takes in one argument (a Graph) and returns the
sum of all nodes in the graph. Your function must include a type annotation for full credit. You
may assume that the passed-in graph is guaranteed to have no cycles. You may have helper
function(s).
Your solution MUST be shorter than 8 lines long.
Answer:
Any of these answers deserves full marks. They require one of the following
type annotations:
sum_of_graph :: Graph -> Int
sum_of_graph :: Graph -> Integer
--- carey's solution
sum_of_graph (Node val edges) =
val + (sumx_aux edges)
where
value (Node val edges) = val + (sumx_aux edges)
sumx_aux edges =
sum [value n | n <- edges]
--- matt’s solution (map + sum)
sum_of_graph (Node val edges) = val + sum (map sum_of_graph edges)
--- matt’s solution (map + fold)
sum_of_graph (Node val edges) = foldl (+) val (map sum_of_graph edges)
--- optionally, students might include a base case like the following, though
observe that it’s not strictly necessary
sum_of_graph (Node val []) = val
--- many other solutions are possible. other neat ones we saw included:
--- - parsing the edges node-by-node, which required:
---
- a mutually recursive helper function
---
- or, “recreating” a new node with value 0, and the tail as its edges
--- - foldl/foldr, but calling sum_of_graph on each edge
Rubric Sketch (negative grading)
●
Perfect (-0 pts)
●
Minor syntax error(s) that did not affect understanding (-1 pts)
○
ex: forgetting the parens for an ADT variant argument
●
Incorrect base case / singleton node (-2 pts)
○
ex: base case has value 0
●
Minor recursive logic bug (-2 pts)
○
requires a fully-working solution, with one minor tweak
○
ex: switching the order of the args to foldl/foldr
○
ex: used sum improperly
●
Major recursive logic bug / multiple minor bugs (-5 pts)
○
ex: recursive solution tries to add a Graph and Integer
○
ex: recursive solution tries to call sum_of_graph [Graph]
○
ex: recursive solution misses multiple levels of children
●
Incorrect/missing type definition (-1 pts)
○
all-or-nothing; did give ECF
○
if
only
submitted typedef, received 1 pt total
●
Did not attempt (-10 pts)
A handful of students noted that our definition of acyclic was unclear (is
this acyclic in the undirected sense, or in the directed sense)? The latter
has a “diamond problem” built-in; we were expecting solutions for the former.
If you tried to deal with this but had a minor logic bug, we gave you full
credit.
4. [10 points] Write a Haskell function called
get_every_nth
that takes in an Integer n and a list
of generic types that returns a sublist of every n
th
element. For example:
get_every_nth 2 ["hi","what's up","hello"] should return ["what's up"]
get_every_nth 5 [31 .. 48] should return [35, 40, 45]
Your function must have a type signature and must use either filter, foldr or foldl. It must be less
than 8 lines long.
Hint: If you use fold, your accumulator doesn't need to be the same type as your returned value
or your input, and a tuple might be useful!
Carey's answer:
get_every_nth :: Integer -> [a] -> [a]
get_every_nth n lst =
map (\tup -> snd tup)
-- or map (\(_,x) -> x)
(filter (\tup -> (fst tup) `mod` n == 0) (zip [1..] lst))
Ruining's answer:
get_every_nth :: Integer -> [a] -> [a]
get_every_nth n lst =
let f = \(res,index) x -> if mod index n == 0 then (x:res, index+1) else
(res,index+1)
-- this 'let' is one line
in reverse( fst (foldl f ([],1) lst))
also acceptable;
(\(x,_) ->x) instead of fst
Possible common mistakes:
-
0/10 for empty/ all wrong
-
2/10 for an ok attempt (correct type, usage of functions is alright)
-
5/10 for good idea
-
7/10 for multiple syntax/edge problems
-
indexing off
-
9/10 for syntax/edge problems (might bump up, not sure)
-
wrong operator/symbol
-
reverse
-
convert tuple to list
-
10/10 for perfect
(comprehensions count as filters)
5. [5 points] Write a Haskell comprehension that generates an infinite list of functions, each of
which takes a single argument x, such that the k
th
function returns x
k
. You may assume that k
starts at 1 for the first generated function, 2 for the second function, etc. For example:
inf_list = [your comprehension here]
head inf_list 9 → returns 9
head (tail inf_list) 9 → returns 81
Answer:
inf_list = [\x -> z^x | z <- [1..]]
– carey's answer
Possible common mistakes:
-
not returning a list of functions ([z^x | z <- [1..]]) -> -3 pts
-
using the wrong operator (neither ** or ^) -> -3 pts
-
extraneous argument in lambda ([\x k -> x^k | k <- [1..]] -> -1 pt
6. [10 points-5/5] Consider the following Python program:
class Comedian:
def __init__(self, joke):
self.__joke = joke
def change_joke(self, joke):
self.__joke = joke
def get_joke(self):
return self.__joke
def process(c):
# line A
c[1] = Comedian("joke3")
c.append(Comedian("joke4"))
c = c + [Comedian("joke5")]
c[0].change_joke("joke6")
def main():
c1 = Comedian("joke1")
c2 = Comedian("joke2")
com = [c1,c2]
process(com)
c1 = Comedian("joke7")
for c in com:
print(c.get_joke())
a. Assuming we run the main function, what will this program print out?
Answer:
Partial credit for this part (a) and the next part (b) is only awarded if
either the student fails to properly take into account a single valid
mutation, or incorporates a single invalid mutation when there wasn't
supposed to be one.
Rubric for MT1 6.a
5 points for:
joke6
joke3
joke4
2.5 points for:
joke6
joke2
joke4
2.5 points for:
joke6
joke3
2.5 points for:
joke6
joke3
joke4
joke5
2.5 points for:
joke1
joke3
joke4
2.5 points for:
joke7
joke3
joke4
All other answers get a zero
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Related Questions
C++ code only...
arrow_forward
In C++, write a Number class that holds a double, and add overloaded operators for +, –, *, /, and assignment. Choose the return values for these functions so that expressions can be chained together, and for efficiency. Write an automatic type conversion operator intdouble( ).
arrow_forward
Question 3
use c++ to Write a template class Point with two class parameters representing the two coordinates of the Point. Include public methods to display and set the data values as well as a function that swaps the values so that, after the swap, the first element is cast into the second and the second is cast into the first. Also write a main function that creates a Point object and calls the public methods.
arrow_forward
Type checking entails what exactly? Explain the differences between static and dynamic type checking, as well as the relative merits of each.
arrow_forward
The differences between value types and reference types applies to parameters. True False
arrow_forward
HELP WITH C+...PASTE INDENTED CODE
Given the code: class Organization {private; int numMembers; // number of members in the organization string *name; // name of the organization string *members; // dynamic array of members}1. Write a function definition for a Constructor to initialize all data members.2. Write a function definition for the Copy Constructor.3. Write a function definition for the Destructor.
arrow_forward
Is there a difference between static and dynamic type checking?
arrow_forward
Book: C++ Programming: From Problem Analysis to Program Design 8th edition, D. S. Malik
In C++
In this programming exercise, you use abstract classes and pure virtual functions to design classes to manipulate various types of accounts. For simplicity, assume that the bank offers three types of accounts: savings, checking, and certificate of deposit, as described next.
Savings accounts: Suppose that the bank offers two types of savings accounts: one that has no minimum balance and a lower interest rate and another that requires a minimum balance and has a higher interest rate.
Checking accounts: Suppose that the bank offers three types of checking accounts: one with a monthly service charge, limited check writing, no minimum balance, and no interest; another with no monthly service charge, a minimum balance requirement, unlimited check writing, and lower interest; and a third with no monthly service charge, a higher minimum requirement, a higher interest rate, and unlimited check…
arrow_forward
LANGUAGE : C++
arrow_forward
PROGRAMMING LANGUAGE :C++
QUESTION;
You need to store hiring date and date of birth for Managers and Employees. You need to create a Date class for this purpose. Create objects of Date class in Manager and Employee classes to store respective dates. You need to write print function in Manager and Employee classes as well to print all information of Managers and Employees. You need to perform composition to implement this task. Create objects of Manager and Employee classes in main function and call print function for both objects.
______________________________________________________________
note : print the specific part of code in following ...
Print Date class here:
Print updated Manager class here:
Print updated Employee class here:
Print main function here:
arrow_forward
c++
Friend function concepts
Do not use operator overloading
Write a Program to design a class complex to represent complex numbers and an input method "void input(float X, float Y)" for setting the values of complex number. Class should use an external friend function "friend complex sum (complex, complex);" to add two complex numbers and should return an object of type complex representing the sum of two complex numbers. Write another method "void show (complex c)" to show the final summation.
arrow_forward
write in c++ (classes)
Problem
Write a C++ program that will display multiple-choice trivia questions, accept the user's answers, and provide a full key and a score at the end.
Question class
Design and implement a class called Question. The Question class contains the following information:
a stem (the text of the trivia question),
an array of 4 multiple choice answers (the text of each possible answer)
the letter of the correct answer (A, B, C, or D), called the key.
This class will be used to represent trivia questions in a trivia game. The following operations should be available for Question objects (use the provided names).
Construct a Question with no values (use empty strings for stem and answers and ‘X’ for the key).
Construct a Question given its 3 components ().
setStem: Set the stem question.
getStem : Return the stem question.
setAnswers : Set the 4 answers given an array. The answers will NOT include the letter (A, B, C, or D).
getAnswer(i) : Return the single answer…
arrow_forward
C++ Code
Step 1: Preparation
For the moment, "comment out" the following under-construction code:
In dynamicarray.h: All function prototypes except the constructors and destructor. Keep the member variables (but we will be replacing them shortly).
In dynamicarray.cpp: All function implementations except the constructors and destructor. You should also remove (not just comment out) INITIAL_CAP, and replace it with a hard-coded 10 inside the default constructor. This will also eventually go away.
In main: Comment out all the code inside the RunPart1Tests function between the linesbool pass = true;
and
return pass;
• Also in main: Comment out all the code in the main function starting with the "Equality comparison" comment and just before the "return 0;" line.
Step 2: Replacing member data and the two constructors
You're going to replace the current member data (arr, len, and capacity) with a single vector of integers. Remember that vectors keep track of their own size and capacity, so…
arrow_forward
The distinction between type equivalence and type compatibility is explained
below.
arrow_forward
Code Should Be In C++
arrow_forward
Write a simple C++ code as I am a beginner.
arrow_forward
C++
Private data and function of a class cannot be accessed from outside function. Explain how it is possible to access then with reference of an example.
arrow_forward
SUBJECT: OOPPROGRAMMING LANGUAGE: C++
ALSO ADD SCREENSHOTS OF OUTPUT.
Write a class Distance to measure distance in meters and kilometers. The class should have appropriate constructors for initializing members to 0 as well as user provided values. The class should have display function to display the data members on screen.
Write another class Time to measure time in hours and minutes. The class should have appropriate constructors for initializing members to 0 as well as user provided values. The class should have display function to display the data members on screen.
Write another class which has appropriate functions for taking objects of the Distance class and Time class to store time and distance in a file.
Make the data members and functions in your program const where applicable
arrow_forward
Create a class in C++ called ADDITION has one integer and one float data member. Use pointer to data member to find their sum and print it from main method and also use the concept of dynamic constructor.
arrow_forward
Define Void Pointer?
arrow_forward
3. Write a C++ program using an overloaded * operator that multiplies two
objects using Arrays and return the value its value. Use class name Arr(). (40)
arrow_forward
programming paradigms
Please write the following functions in Haskell. Please also write type declarations for each function, including type classes, wherever necessary.
1. Modify isGodzilla from today's lecture to isNum where the function accepts an integer as an input parameter and outputs True if this integer matches the number in the function.
2. Write a function fibList that uses the fib function from today's lecture. fibList accepts a number n as parameter and outputs a list of the numbers in the Fibonacci series up to n. Note that fibList will use a list comprehension involving fib.
3. Write a function justHighScores that takes the list generated as output of the gradeBook function and returns a list of students who score >= 95. Please use the isHighScorer function from today's lecture in justHighScores. You will also have to implement the gradeBook function discussed in class today.
4. Modify the function lastElement from today's lecture to getSecondLast. The function…
arrow_forward
Write in c++.
arrow_forward
c++
-Non-constructor can be overloaded. True or false
-Constructors can be overloaded. True or false
-what should I use if I want to express about width with type In UML?
arrow_forward
Please write a main method in C that calls and implements all of the functions above.
arrow_forward
CPS506 Lab 6
Haskell: Type classes and custom types
Preamble
In this lab you'll create a custom type in Haskell and make it an instance of several built-in Haskell type-classes.
Getting Started
The provided cabal project defines a module called Lab6. This module will define a custom type called DigitalTime. The DigitalTime type will be used to represent time as a 3-tuple of integers. One for hour, minute, and second, respectively. Thus, the type definition should look like this:
data DigitalTime = DigitalTime (Int, Int, Int) Next, you will implement several type classes over this type. These type classes and their operations can be found below. Assume that the hour range is 1-12. Do not use 24h time.
Type Classes to Implement
Show:
show DigitalTime (h, m, s) Print the time in the format "<hh:mm:ss>"
Eq:
(==) (DigitalTime (h1, m1, s1)) (DigitalTime (h2, m2, s2)) Two times are considered equal if they have the same hour, minute, and second values.
Ord:
(<=) (DigitalTime (h1, ml,…
arrow_forward
need help with c++...paste indented code plzz
arrow_forward
SEE MORE QUESTIONS
Recommended textbooks for you
Database System Concepts
Computer Science
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:McGraw-Hill Education
Starting Out with Python (4th Edition)
Computer Science
ISBN:9780134444321
Author:Tony Gaddis
Publisher:PEARSON
Digital Fundamentals (11th Edition)
Computer Science
ISBN:9780132737968
Author:Thomas L. Floyd
Publisher:PEARSON
C How to Program (8th Edition)
Computer Science
ISBN:9780133976892
Author:Paul J. Deitel, Harvey Deitel
Publisher:PEARSON
Database Systems: Design, Implementation, & Manag...
Computer Science
ISBN:9781337627900
Author:Carlos Coronel, Steven Morris
Publisher:Cengage Learning
Programmable Logic Controllers
Computer Science
ISBN:9780073373843
Author:Frank D. Petruzella
Publisher:McGraw-Hill Education
Related Questions
- C++ code only...arrow_forwardIn C++, write a Number class that holds a double, and add overloaded operators for +, –, *, /, and assignment. Choose the return values for these functions so that expressions can be chained together, and for efficiency. Write an automatic type conversion operator intdouble( ).arrow_forwardQuestion 3 use c++ to Write a template class Point with two class parameters representing the two coordinates of the Point. Include public methods to display and set the data values as well as a function that swaps the values so that, after the swap, the first element is cast into the second and the second is cast into the first. Also write a main function that creates a Point object and calls the public methods.arrow_forward
- Type checking entails what exactly? Explain the differences between static and dynamic type checking, as well as the relative merits of each.arrow_forwardThe differences between value types and reference types applies to parameters. True Falsearrow_forwardHELP WITH C+...PASTE INDENTED CODE Given the code: class Organization {private; int numMembers; // number of members in the organization string *name; // name of the organization string *members; // dynamic array of members}1. Write a function definition for a Constructor to initialize all data members.2. Write a function definition for the Copy Constructor.3. Write a function definition for the Destructor.arrow_forward
- Is there a difference between static and dynamic type checking?arrow_forwardBook: C++ Programming: From Problem Analysis to Program Design 8th edition, D. S. Malik In C++ In this programming exercise, you use abstract classes and pure virtual functions to design classes to manipulate various types of accounts. For simplicity, assume that the bank offers three types of accounts: savings, checking, and certificate of deposit, as described next. Savings accounts: Suppose that the bank offers two types of savings accounts: one that has no minimum balance and a lower interest rate and another that requires a minimum balance and has a higher interest rate. Checking accounts: Suppose that the bank offers three types of checking accounts: one with a monthly service charge, limited check writing, no minimum balance, and no interest; another with no monthly service charge, a minimum balance requirement, unlimited check writing, and lower interest; and a third with no monthly service charge, a higher minimum requirement, a higher interest rate, and unlimited check…arrow_forwardLANGUAGE : C++arrow_forward
- PROGRAMMING LANGUAGE :C++ QUESTION; You need to store hiring date and date of birth for Managers and Employees. You need to create a Date class for this purpose. Create objects of Date class in Manager and Employee classes to store respective dates. You need to write print function in Manager and Employee classes as well to print all information of Managers and Employees. You need to perform composition to implement this task. Create objects of Manager and Employee classes in main function and call print function for both objects. ______________________________________________________________ note : print the specific part of code in following ... Print Date class here: Print updated Manager class here: Print updated Employee class here: Print main function here:arrow_forwardc++ Friend function concepts Do not use operator overloading Write a Program to design a class complex to represent complex numbers and an input method "void input(float X, float Y)" for setting the values of complex number. Class should use an external friend function "friend complex sum (complex, complex);" to add two complex numbers and should return an object of type complex representing the sum of two complex numbers. Write another method "void show (complex c)" to show the final summation.arrow_forwardwrite in c++ (classes) Problem Write a C++ program that will display multiple-choice trivia questions, accept the user's answers, and provide a full key and a score at the end. Question class Design and implement a class called Question. The Question class contains the following information: a stem (the text of the trivia question), an array of 4 multiple choice answers (the text of each possible answer) the letter of the correct answer (A, B, C, or D), called the key. This class will be used to represent trivia questions in a trivia game. The following operations should be available for Question objects (use the provided names). Construct a Question with no values (use empty strings for stem and answers and ‘X’ for the key). Construct a Question given its 3 components (). setStem: Set the stem question. getStem : Return the stem question. setAnswers : Set the 4 answers given an array. The answers will NOT include the letter (A, B, C, or D). getAnswer(i) : Return the single answer…arrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education
Database System Concepts
Computer Science
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:McGraw-Hill Education
Starting Out with Python (4th Edition)
Computer Science
ISBN:9780134444321
Author:Tony Gaddis
Publisher:PEARSON
Digital Fundamentals (11th Edition)
Computer Science
ISBN:9780132737968
Author:Thomas L. Floyd
Publisher:PEARSON
C How to Program (8th Edition)
Computer Science
ISBN:9780133976892
Author:Paul J. Deitel, Harvey Deitel
Publisher:PEARSON
Database Systems: Design, Implementation, & Manag...
Computer Science
ISBN:9781337627900
Author:Carlos Coronel, Steven Morris
Publisher:Cengage Learning
Programmable Logic Controllers
Computer Science
ISBN:9780073373843
Author:Frank D. Petruzella
Publisher:McGraw-Hill Education