CSE 428 - Solutions To Exercises On ML
CSE 428 - Solutions To Exercises On ML
The superscript "(d)" stands for "difficult". Exercises similar to those marked with "(d)" might appear in
candidacy exams, but not in the standard exams of CSE 428.
1. Define a function which computes the product of all integers between m and n (with n >= m) inclusive.
Use this function to define the function Cn,k (the number of combinations of n elements taken k by k),
which is defined by
Cn,k = n!/(k!*(n-k)!)
Solution
fun prod(m,n) = if n <= m then m else n * prod(m,n-1);
2. Define a function
power(n,m) = nm
Solution
fun power(n,m) = if m=0 then 1 else n * power(n,m-1);
3. The positive integer square root of a non-negative integer is a function introot such that: if introot
m = n, then n is the largest integer such that n2 is less than or equal to m. Define the function introot
in ML.
Solution
fun introot m = let fun aux(k,m) = if k*k > m then k-1 else aux(k+1,m)
in aux(0,m)
end;
4. In ML, like in any other language, the if-then-else construct is non-strict, i.e. only one of the branches
is evaluated, depending on the the result of the test. What would be the consequences for recursive
definitions if the if-then-else were strict (meaning that first both the branches are evaluated, and then
one of the results is picked, depending on the result of the test), and pattern-matching were not
available?
1 of 6 2/12/2021, 10:12 PM