I was required to write a set of functions for problems in class. I think the way I wrote them was a bit more complicated than they needed to be. I had to implement all the functions myself, without using and pre-defined ones. I'd like to know if there are any quick any easy "one line" versions of these answers?
- Sets can be represented as lists. The members of a set may appear in any order on the list, but there shouldn't be more than one occurrence of an element on the list.
(a) Define dif(A, B) to compute the set difference of A and B, A-B.
(b) Define cartesian(A, B) to compute the Cartesian product of set A and set B, { (a, b) | a∈A, b∈B }.
(c) Consider the mathematical-induction proof of the following: If a set A has n elements, then the powerset of A has 2n elements. Following the proof, define powerset(A) to compute the powerset of set A, { B | B ⊆ A }.
(d) Define a function which, given a set A and a natural number k, returns the set of all the subsets of A of size k.
(* Takes in an element and a list and compares to see if element is in list*)
fun helperMem(x,[]) = false
| helperMem(x,n::y) =
if x=n then true
else helperMem(x,y);
(* Takes in two lists and gives back a single list containing unique elements of each*)
fun helperUnion([],y) = y
| helperUnion(a::x,y) =
if helperMem(a,y) then helperUnion(x,y)
else a::helperUnion(x,y);
(* Takes in an element and a list. Attaches new element to list or list of lists*)
fun helperAttach(a,[]) = []
helperAttach(a,b::y) = helperUnion([a],b)::helperAttach(a,y);
(* Problem 1-a *)
fun myDifference([],y) = []
| myDifference(a::x,y) =
if helper(a,y) then myDifference(x,y)
else a::myDifference(x,y);
(* Problem 1-b *)
fun myCartesian(xs, ys) =
let fun first(x,[]) = []
| first(x, y::ys) = (x,y)::first(x,ys)
fun second([], ys) = []
| second(x::xs, ys) = first(x, ys) @ second(xs,ys)
in second(xs,ys)
end;
(* Problem 1-c *)
fun power([]) = [[]]
| power(a::y) = union(power(y),insert(a,power(y)));
I never got to problem 1-d, as these took me a while to get. Any suggestions on cutting these shorter? There was another problem that I didn't get, but I'd like to know how to solve it for future tests.
- (staircase problem) You want to go up a staircase of n (>0) steps. At one time, you can go by one step, two steps, or three steps. But, for example, if there is one step left to go, you can go only by one step, not by two or three steps. How many different ways are there to go up the staircase? Solve this problem with sml. (a) Solve it recursively. (b) Solve it iteratively.
Any help on how to solve this?