0% found this document useful (0 votes)
125 views6 pages

Cuhk Ierg4120 hw3 Solutions

This document contains a 10 question assignment on functional programming in OCaml. It covers topics like defining record types, references, maps, functors, modules, and more. For each question, students are asked to write OCaml code to implement the given task, such as defining a student record type, using references to increment a value, creating and manipulating maps, writing functors and modules, and more. Detailed comments are requested for each answer.

Uploaded by

dhs6f9so1z5a
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
125 views6 pages

Cuhk Ierg4120 hw3 Solutions

This document contains a 10 question assignment on functional programming in OCaml. It covers topics like defining record types, references, maps, functors, modules, and more. For each question, students are asked to write OCaml code to implement the given task, such as defining a student record type, using references to increment a value, creating and manipulating maps, writing functors and modules, and more. Detailed comments are requested for each answer.

Uploaded by

dhs6f9so1z5a
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

CUHK IERG4120 Functional Programming

Assignment 3

November 2023

Attention
- Please separate your answers into different .ml program files as modules if
necessary.
- Write necessary and expressive comments for better information conveying.
- Separate the answer to each question by comments (e.g., (* Q1 *)).

Q1. (10/10) Define an OCaml record type student to represent student names
and GPAs. It should be possible to mutate the value of a student’s GPA. Write
an expression defining a student with student name ”Alice” and GPA 3.7. Then
write an expression to mutate Alice’s GPA to 4.0.
Q2. (10/10) Define a reference to a function as follows:
let inc = ref (fun x -> x + 1)
Write code that uses inc to produce the value 4120.
Q3. (10/10) To create a standard library map, we first have to use the Map.Make
functor to produce a module that is specialized for the type of keys we want.
Type the following in utop:
# module CharMap = Map.Make(Char);;
The output tells you that a new module named CharMap has been defined,
and it gives you a signature for it. Find the values empty, add, and remove in
that signature. Explain their types in your own words.
Q4. (10/10) The Map.Make functor requires its input module to match the
Map.OrderedType signature. Look at that signature as well as the signature
for the Char module. Explain in your own words why we can pass Char as an
argument to Map.Make.
Q5. (10/10) Using the CharMap you just made, create a map that contains the
following bindings:
- ‘A’ maps to ”Alpha”
- ‘E’ maps to ”Echo”

1
- ‘S’ maps to ”Sierra”
- ‘V’ maps to ”Victor”
Use CharMap.find to find the binding for ’E’.
Now remove the binding for ’A’. Use CharMap.mem to find whether ’A’ is still
bound.
Use CharMap.bindings to convert your map into an association list.
Q6. (10/10) Write a module type ToString that specifies a signature with an
abstract type t and a function to_string : t -> string.
Q7. (10/10) Write a functor Print that takes as input a module named M of
type ToString. The module returned by your functor should have exactly one
value in it, print, which is a function that takes a value of type M.t and prints
a string representation of that value.
Q8. (10/10) Here is a module for the module type from the previous exercise:
1 module Complex : ComplexSig = struct
2 type t = float * float
3 let zero = (0. , 0.)
4 let add ( r1 , i1 ) ( r2 , i2 ) = r1 +. r2 , i1 +. i2
5 end

Investigate what happens if you make the following changes (each indepen-
dently), and explain why any errors arise:
- Remove zero from the structure
- Remove add from the signature
- Change zero in the structure to let zero = 0, 0
Q9. (10/10) Addition assignment operator (+=). The C language and many
languages derived from it, such as Java, has an addition assignment operator
written a += b and meaning a = a + b. Pls implement such an operator in
OCaml. The operator’s type should be int ref -> int -> unit. Here’s some
code to get you started:
1 let ( +:= ) x y = ...
2 (* And here is an example of usage : *)
3 # let x = ref 1;;
4 # x +:= 4120;;
5 # ! x ;;
6 - : int = 4121;;

Q10. (10/10) Define x, y, and z as follows:

2
1 let x = ref 0
2 let y = x
3 let z = ref 0

Predict the value of the following series of expressions:


1 # x == y ;;
2 # x == z ;;
3 # x = y ;;
4 # x = z ;;
5 # x := 1;;
6 # x = y ;;
7 # x = z ;;

Check your answers in utop.

3
Q1. Define an OCaml student type with two fields: student name and GPA.

1 (* type definition of student *)


2 type student = {
3 name: string;
4 mutable gpa: float;
5 };;
6

7 (* initialization of alice*)
8 let alice = {name = "Alice"; gpa = 3.7;};;
9

10 (* update the field gpa of alice *)


11 let () = alice.gpa <- 4.0;;

Q2. Define a reference to the given inc function.

1 (* The given code*)


2 let inc = ref (fun x -> x + 1)
3

4 (* User code *)
5 let ierg4120 =
6 let inc = ref (fun x -> x + 1)
7 in !inc 4120

Q3. In the CharMap module, [key] is the type of the keys, which is synonymous
with [char], ['a] is the type of values and [t] is the abstract type of the
character map. [empty] is an empty character map. Its type is ['a t] because
it is a map whose value type is not yet known. [add] takes a key of type [key],
a value of type ['a], an existing map of type ['a t], and returns a new map
with a binding from that key to that value. [remove] takes a key of type [key]
and an existing map of type ['a t], and returns a new map without a binding
for [key].
Q4. [Char] matches the [Map.OrderedType] signature because it contains a
type named [t] as well as an ordering function [compare : t -> t -> int].

Q5. User-Char Map.

1 module CharMap = Map.Make(Char)


2

3 let map = CharMap.(


4 empty
5 |> add 'A' "Alpha"
6 |> add 'E' "Echo"
7 |> add 'S' "Sierra"

4
8 |> add 'V' "Victor"
9 )
10

11 (* "Echo" *)
12 let echo = CharMap.find 'E' map
13 let map' = CharMap.remove 'A' map
14 (* false *)
15 let a_exists = CharMap.mem 'A' map'
16 (* [('E', "Echo"); ('S', "Sierra"); ('V', "Victor")] *)
17 let bindings = CharMap.bindings map'

Q6. Module ToString

1 module type ToString = sig


2 type t
3 val to_string: t -> string
4 end

Q7. Functor Print

1 module Print (M : ToString) = struct


2 (* effects: print a string representation of [M.t] *)
3 let print v = print_string (M.to_string v)
4 end

Q8. Complex

1 module Complex : ComplexSig = struct


2 type t = float * float
3 let zero = (0., 0.)
4 let add (r1,i1) (r2,i2) = r1 +. r2, i1 +. i2
5 end

• Remove zero from the structure: Signature mismatch: The value zero is
required but not provided.
• Remove ‘add‘ from the signature: No error, but now clients can’t add
complex numbers.
• Change zero in the structure to let zero = 0, 0: Signature mismatch:
Values do not match: val zero : int * int is not included in val zero : t

Q9. Additional assignment.

1 let (+:=) x y =
2 x := !x + y

5
Q10. Physical equality checking.

1 (* original definition *)
2 let x = ref 0
3 let y = x
4 let z = ref 0
5

6 (* checking assertions *)
7 let _ =
8 let x = ref 0 in
9 let y = x in
10 let z = ref 0 in
11

12 assert (x == y);
13 assert (not (x == z));
14 assert (x = y);
15 assert (x = z);
16 x := 1;
17 assert (x = y);
18 assert (not (x = z))

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy