# LOOK UP A SYMBOL IN THE TABLE USING THE "MOVE TO FRONT" METHOD. The # table is a vector held in the global variable sym.table. The table is # modified by moving the symbol found to the front, while symbols before it # move back one to make room. The value returned is the index of the symbol # in the table (before it was moved to the front), which is a rough indication # of how long it took to find it. # # This function will work for symbols that are either character strings or # integers (and some other things as well). # # This function considers it to be an error if the symbol isn't in the table. # If this happens, the program is terminated with an error message. (This # probably isn't what one would want to do in a real application.) # # A note on R: Assignments to global variables inside functions are done # using "<<-" rather than "<-". That's how R can tell that the assignment # isn't to a local variable of the same name. mtf.lookup <- function (s) { # Find where in the table the symbol is found. i <- 1 while (sym.table[i]!=s) { i <- i + 1 if (i>length(sym.table)) { stop("The symbol being looked for isn't in the table!") } } # Move symbols before the one found forward one position, and then put # the symbol found at the front of the table. j <- i while (j>1) { sym.table[j] <<- sym.table[j-1] j <- j - 1 } sym.table[1] <<- s # Return the position of the symbol before it was moved to the front. i }