9. Modules:  Problems

Last revision:  February 9 1998

Author: YourNameGoesHere

1: plotWalk

Create a functioning program Module plotWalk[] that contains all of the following steps with a formal parameter m instead of the number 50.  Make names local whenever possible, and consider using local constants where appropriate.

dirList = {{1,0},{0,1},{-1,0},{0,-1}}

ranDirec := Part[dirList, Random[Integer,{1,4}]]

ranSteps[n_] := Table[ranDirec,{n}]

origin = {0,0}

stops[n_] := FoldList[Plus,origin,ranSteps[n]]

ListPlot[stops[50], PlotJoined->True, PlotRange->All]

2: base16String2Num

Create a functioning program Module base16String2Num[] that contains all of the following steps with a formal parameter s instead of the string "12aB".  Make names local whenever possible, and consider using local constants where appropriate.

string1 = ToUpperCase["12aB"]

list1 = ToCharacterCode[string1] - 48

MakeABCDEFInto101112131415[i_] := 
	If[i>=17, i-7, i]
(* Because we want A's to be 10's and the
character code of A is 65, we must subtract 7
more from the code of each A, B, C, D, E, and F.
This function will allow us to do so *)

list2 = Map[MakeABCDEFInto101112131415,list1]

list3 = Reverse[
           Table[
              16^j,
              {j,0,StringLength["12aB"]-1}
           ]
        ]

list4 = list2 * list3

Apply[Plus,list4]

3: variable & function scope; side-effects

In the following code, determine how many different names (variables and functions) there are, the scope of each, and the side effects of any functions.  Also, write sentences explaining exactly what happens in each function.  (You may need to use the "?" command to determine how If[] works.)  Note that on your midterm you may have a problem, similar to this one, on which you will not be able to use a computer to answer the question; you should hone your programming reading skills as well as writing skills.  You may also wish to assess the style of this code.

pet = "dog"

pet2 = "cat"

procreate[animal_] := {animal,animal}

runFarmA[purchase_] :=
   Module[{pet, procreate}, 
      pet = "pig";
      procreate[animal_] := {animal,animal,animal};
      {procreate["sheep"], procreate[pet], purchase}
   ]

runFarmB[purchase_] :=
   Module[{pet, procreate},
      pet = "pig";
      pet2 = "declawed cat";
      procreate[animal_] := {animal,animal,animal};
      {procreate["sheep"], procreate[pet], purchase}
   ]

declaw[anAnimal_] := 
   If[anAnimal=="cat", "declawed cat", anAnimal]

4 Extra Credit: myInterpolate

Complete the definition of myInterpolate[], a function which uses the divided difference quotients algorithm from the section to return the desired polynomial back to the user.  myInterpolate[] should return the same polynomials, then, as the Mathematica function InterpolatingPolynomial[].  Use a Fold[] command to produce the polynomial.