# OCaml | homework | Data structure | assignment作业 – CSE 216 Homework I

### CSE 216 Homework I

OCaml | homework | Data structure | assignment作业 – 这是利用OCaml 进行训练的代写, 对OCaml 的编程流程进行训练解析, 是比较典型的OCaml 等代写方向, 这个项目是assignment代写的代写题目，OCaml 是非常小众的语言

This homework document consists of 3 pages. Carefully read the entire document before you start coding. Note: All functions, unless otherwise specified, should be polymorphic (i.e., they should work with any data type). For example, if you are writing a method that should work for lists, the type must be’a list, and notint list.

#### 1 Recursion and Higher-order Functions (60 points)

In this section, you may not use any functions available in the OCaml library that already solves all or most of the question. For example, OCaml provides aList.revfunction, but you may not use that in this section.

``````1.Write a recursive functionpow, which takes two integer parametersxandn, and returnsxn. Also write (6)
a functionfloatpow, which does the same thing, but forxbeing a float (nis still an integer). You may
assume thatnwill always be non-negative.
``````
``````2.Write a functioncompressto remove consecutive duplicates from a list. (6)
# compress ["a";"a";"b";"c";"c";"a";"a";"d";"e";"e";"e"];;
``````
• : string list = [“a”; “b”; “c”; “a”; “d”; “e”]
``````3.Write a functionremoveifof the type'a list -> ('a -> bool) -> 'a list, which takes a list and (6)
a predicate, and removes all the elements that satisfy the condition expressed in the predicate.
# remove_if [1;2;3;4;5] (fun x -> x mod 2 = 1);;
``````
• : int list = [2; 4]
``````4.Write a functionequivsof the type('a ->'a -> bool) ->'a list ->'a list list, which par- (6)
titions a list into equivalence classes according to the equivalence function.
# equivs (=) [1;2;3;4];;
``````
• : int list list = [[1];[2];[3];[4]]

# equivs (fun x y -> (=) (x mod 2) (y mod 2)) [1; 2; 3; 4; 5; 6; 7; 8];;

• : int list list = [[1; 3; 5; 7]; [2; 4; 6; 8]]
``````5.Some programming languages (like Python) allow us to quicklyslicea list based on two integersiand (6)
j, to return the sublist from indexi(inclusive) andj(not inclusive). We want such a slicing function
in OCaml as well.
Write a functionsliceas follows: given a list and two indices,iandj, extract the slice of the list
containing the elements from theith(inclusive) to thejth(not inclusive) positions in the original list.
# slice ["a";"b";"c";"d";"e";"f";"g";"h"] 2 6;;
``````
• : string list = [“c”; “d”; “e”; “f”]
``````Invalid index arguments should be handledgracefully. For example,
# slice ["a";"b";"c";"d";"e";"f";"g";"h"] 3 2;;
``````
• : string list = []

# slice [“a”;”b”;”c”;”d”;”e”;”f”;”g”;”h”] 3 20;

• : string list = [“d”;”e”;”f”;”g”;”h”];
``````6.Write a function calledcomposition, which takes two functions as its input, and returns their compo- (6)
sition as the output.
``````
``````# let square_of_increment = composition square increment;;
val square_of_increment : int -> int = <fun>
# square_of_increment 4;; (* increments 4 to 5, and THEN computes square *)
``````
• : int = 25 7.Write a function calledequivon, which takes three inputs: two functionsfandg, and a listlst. It (6) returnstrueif and only if the functionsfandghave identical behavior on every element oflst.

# let f i = i * i;;

val f : int -> int =

# let g i = 3 * i;;

val g : int -> int =

# equiv_on f g [3];;

• : bool = true

# equiv_on f g [1;2;3];;

• : bool = false 8.Write a functions calledpairwisefilterwith two parameters: (i) a functioncmpthat compares two (6) elements of a specificTand returns one of them, and (ii) a listlstof elements of that same typeT. It returns a list that appliescmpwhile taking two items at a time fromlst. Iflsthas odd size, the last element is returned as is.

# pairwisefilter min [14; 11; 20; 25; 10; 11];;

• : int list = [11; 20; 10]

# pairwisefilter shorter [“and”; “this”; “makes”; “shorter”; “strings”; “always”; “win”];;

• : string list = [“and”; “makes”; “always”; “win”] 9.Write thepolynomialfunction, which takes a list of tuples and returns the polynomial function corre- (6) sponding to that list. Each tuple in the input list consists of (i) the coefficient, and (ii) the exponent.

# let f = polynomial [3, 3;; -2, 1; 5, 0];;

val f : int -> int =

# f 2;;

• : int = 25

10.Thepower setof a setSis the set of all subsets ofS(including the empty set and the entire set). (6) Write a functionpowersetof the type’a list -> ‘a list list, which treats lists as unordered sets, and returns the powerset of its input list. You may assume that the input list has no duplicates.

# powerset [3; 4; 10];;

• : int list list = [[]; [3]; [4]; [10]; [3; 4]; [3; 10]; [4; 10]; [3; 4; 10]];

#### 2 Data Types (40 points)

``````1.Let us define a language for expressions in Boolean logic: (10)
type bool_expr =
| Lit of string
| Not of bool_expr
| And of bool_expr * bool_expr
| Or of bool_expr * bool_expr
using which we can write expressions in prefix notation. E.g., (ab)(a) isOr(And(Lit("a"), Lit("b")),
Not(Lit("a"))). Your task is to write a functiontruthtable, which takes as input a logical expression
in two literals and returns its truth table as a list of triples, each a tuple of the form:
(truth-value-of-first-literal, truth-value-of-second-literal, truth-value-of-expression)
For example,
# (* the outermost parentheses are needed for OCaml to parse the third argument
correctly as a bool_expr *)
# truth_table "a" "b" (And(Lit("a"), Lit("b")));;
``````
• : (bool * bool * bool) list = [(true, true, true); (true, false, false); (false, true, false); (false, false, false)]
``````2.In this question you will use higher-order functions to implement an interpreter for a simple stack-based (30)
evaluation language. This language has a fixed set of commands:
``````
• startInitializes an empty stack. This is always the first command in a program and never appears again.
• (push n)Pushes the specified integernon to the top of the stack. This command is always parenthesized.
• popRemoves the top element of the stack.
• addPops the top two elements of the stack, computes their sum, and pushes the result back on to the stack.
• multPops the top two elements of the stack, computes their product, and pushes the result back on to the stack.
• clonePushes a duplicate copy of the top element on to the stack.
• kpopPops the top elementkof the stack, and ifkis a positive number, popskmore elements (or the stack becomes empty, whichever happens sooner).
• haltTerminates the stack evaluation program. This is always the last command. Your task is to define the stack Data structure in OCaml (10 points), and then implement the above commands (20 points). Your stack must be implemented as a list. A complete running example would look something like the following:
``````# start (push 2) (push 3) (push 4) mult add halt;;
``````
• : list int = [14]
``````You may assume that only valid commands will be provided. As such, you do not have to worry about
exception handling.
``````

NOTES:

• Late submissionsoruncompilable codewill not be graded.
• Please remember to verify what you are submitting. Make sure you are, indeed, submitting what you think you are submitting!
• What to submit? A single.zipfile comprising three.mlfiles. The first file must be namedhw1.ml, and should contain your code for the ten questions in section 1 of this assignment. The second file must be namedhw1-bool.ml, and this should contain your code for question 2.1 (Boolean logic). Finally, the third file must be namedhw1-stack.ml, with your code for question 2.2 (stack evaluation language). This assignment will be graded by a script, so be absolutely sure that the submission follows this structure.
``````
``````