Principles 2024 – 2025 CSCI-2041 Fall
Final Exam 2 Exam Review Questions
with Verified Solutions | 100% Pass
Guaranteed | Graded A+
Administrator
[COMPANY NAME] [Company address]
, Name: ID#: X500: @umn.edu A
CS 2041: Practice Final SOLUTION
Fall 2018
University of Minnesota
Exam period: 20 minutes
Points available: 40
Background: OCaml’s standard library has muta- 1 # let table = Hashtbl.create 20;;
ble, polymorphic hash table implementation which 2 # Hashtbl.add table "Goku" 8001;;
maps keys to values in the Hashtbl module which 3 # Hashtbl.add table "Krillin" 1770;;
4# Hashtbl.add table "Piccolo" 3500;;
is demonstrated in a REPL nearby. Like the tree
5 # Hashtbl.add table "Vegeta" 18000;;
maps we created, Hashtbl provides higher-order 6
func- tions for operating on the key/value # let kpower = Hashtbl.find_opt table "Krillin";;
7
associations in the map. val kpower : int option = Some 1770
8
9 # let gpower = Hashtbl.find_opt table "Gohan";;
Problem 1 (5 pts): Write a function print_all 10 val gpower : int option = None
which prints out all key/value bindings in a hash ta- 11
12 # #use "hash_funcs.ml";;
ble of string/integers. Use the higher-order function 13 val print_all : (string, int) Hashtbl.t -> unit = <fu
Hashtbl.iter func tbl where func is passed keys 14 val total_power : (’a, int) Hashtbl.t -> int = <fun>
and values from the hash table and returns unit. It 15
is demonstrated in the REPL session. 16 # print_all table;; (* demo print_all *)
17 Krillin -> 1770
18 Vegeta -> 18000
SOLUTION 19 Piccolo -> 3500
20 Goku -> 8001
1 let print_all table = 21 - : unit = ()
2 let print k v = 22
3 printf "%s -> %d\n" k v 23 # total_power table;; (* demo total_power *)
4 in 24 - : int = 31271
5 Hashtbl.iter print table;
6 ;;
Problem 2 (5 pts): Write a function SOLUTION
total_power which totals the values stored in a 1 let total_power table =
2 let total k v sum =
hash table with integer values. Use the higher-order 3 sum+v
func- tion Hashtbl.fold func tbl initial where 4 in
func is passed keys, values, and a running total. 5 Hashtbl.fold total table 0
It is demonstrated in the REPL session. 6 ;;
Problem 3 (5 pts): A5’s Calculon drew a distinction between a lambda expression and a closure.
Describe the similarities and differences between these two things.
SOLUTION: The parser produces lambda expressions which are part of the parse tree. They have a pa-
rameter and a body of code to execute. The evaluator produces a Closure which is a variant of data_t
like IntDat and BoolDat. Closure’s also have a parameter and code to evaluate when applied but add a
variable map which tracks all variables that were defined at the time the Closure was created.
2A