GIML: Tutorial Two


Tutorial two : Types

  1. Predict the type of each of these objects. Check your answer by entering each followed by the semicolon. ("two", true, 2); ["two", true, 2]; ((1,2),(3,4,5)); [[1,2],[3,4,5]]; [[],[],[]]; ("andrew",size "andrew"); (["andrew"="andrew","andrew"="ben"],size "andrew", size);
  2. Consider the following bindings. Try to predict the result before executing them. val (a,b) = (5,6); val (c,d) = (2,("xx","yy")); val (e,(f,g)) = (1,(2,3)); val (l,m,n) = ("xx",(1,2)); That last binding will fail as the left and right hand sides are incompatible. val (p, _ ) = (12, 10); val (q, 10) = (12, 10); val (r, 11) = (12, 10); Note the failed binding again. val u = 1::[2,3]; val v::w = 1::[2,3]; val h::t = [4,5,6]; Be sure that you understand how the final example works.
  3. Consider the type of each of the following functions fun fone(x:int) = [x,x,x]; fun ftwo(x) = (x,x,x); fun fthree(x,y) = [x ^ "b", y]; fun ffour(x,y,z) = (x+(size y),z);
  4. Find out the type of each of the in-built functions explode, rev, hd and tl. Try each function on a list or a string as appropriate. Make a note of each of the following: Evaluate each of the following; try to predict the result. hd(explode "south"); hd(tl(explode "north")); hd(rev(explode "east")); hd(tl(rev(explode "west"))); Optional Questions:
  5. The function composition operator is o (say of). We can use it to create functions from functions. val first = hd o explode; val second = hd o tl o explode; Create the functions third, fourth and last in a similar manner. You should find that these functions extract a single character from a string. Notice that in a chain of composed functions the last is applied first.

    Note for Moscow ML users

  6. Use the functions first, second ... to create the following: fun roll s = fourth s ^ first s ^ second s ^ third s; fun exch s = second s ^ first s ^ third s ^ fourth s; Test these functions on some four character string such as "ache" and "vile". To save typing you may use the function map - however as this is a higher order function which we have not yet covered you must not attempt to understand how it works. val words = ["ache", "vile", "amid", "evil", "ogre"]; map roll words; map exch words; The two permutations roll and exch can be used to generate any permutation of four characters. For example val what = roll o roll o roll o exch o roll; What's what "what"? Using only function composition on roll and exch define the functions which perform the following. fb "seat" -> "eats" fc "silt" -> "slit" fd "more" -> "rome" Warning : do not apply fb to "ears"
Hints:
Why not try the second self assessment now.
Now would be a good time to tackle Diversion: Distorting Bitmaps