Standard ML Programming/Examples and Exercises
Appearance
Values and Functions
[edit | edit source]- Indicate the identifiers, keywords, and special constants in the following piece of code. What is the value of the second
a
?
val a = 5 val b = 9 val a = 2*a+b;
- Construct a tuple with 4 positions and 3 components.
- What is the type of t?
fun f a = 2 val t = (true,f,f 1);
- Write a function that returns the value 2 for the arguments 0, 1 and 2 and returns 3 for all other arguments.
- Write a function that returns -1 for all negative and +1 for all positive arguments and 0 for the argument 0.
- Create a function min(a:int,b:int) that returns the smaller one of its 2 arguments. Do the separation of the argument values in 3 different ways. Using a Cartesian argument-pattern, using a projection and using a local declaration.
(solutions to this chapter are here)
Recursion
[edit | edit source]- Create a function power9(x) that calculates the 9th power of x. Preferably using as few multiplications as possible.
- Calculate the greatest common denominator from 2 positive integer arguments.
- Calculate mul(n,z)=n*z without using the * operator for and
- Calculate power2(n) by only using addition and resursion. (hint: it is possible to rewrite the square function as a summation of natural numbers.)
(solutions to this chapter are here)