Unformatted text preview:

166CS 538 Spring 2008©Equality Checking in SchemeIn Scheme = is used to test fornumeric equality (includingcomparison of different numerictypes). Non-numeric argumentscause a run-time error. Thus(= 1 1) ⇒ #t(= 1 1.0) ⇒ #t(= 1 2/2) ⇒ #t(= 1 1+0.0i) ⇒ #t167CS 538 Spring 2008©To compare non-numeric values,we can use either:pointer equivalence (do the twooperands point to the sameaddress in memory)structural equivalence (do the twooperands point to structures withthe same size, shape andcomponents, even if they are indifferent memory locations)In general pointer equivalence isfaster but less accurate.Scheme implements both kinds ofequivalence tests.(eqv? obj1 obj2)This tests if obj1 and obj2 arethe exact same object. This worksfor atoms and pointers to thesame structure.168CS 538 Spring 2008©(equal? obj1 obj2)This tests if obj1 and obj2 arethe same, component bycomponent. This works foratoms, lists, vectors and strings.(eqv? 1 1) ⇒ #t(eqv? 1 (+ 0 1))⇒ #t(eqv? 1/2 (- 1 1/2))⇒ #t(eqv? (cons 1 2) (cons 1 2))⇒#f(eqv? "abc" "abc")⇒ #f(equal? 1 1)⇒ #t(equal? 1 (+ 0 1))⇒ #t(equal? 1/2 (- 1 1/2))⇒ #t(equal? (cons 1 2) (cons 1 2))⇒#t(equal? "abc" "abc")⇒ #tIn general it is wise to use equal?unless speed is a critical factor.169CS 538 Spring 2008©I/O in SchemeScheme has simple read and writefunctions, directed to the“standardin” and “standard out” files.(read)Reads a single Scheme object (anatom, string, vector or list) fromthe standard in file. No quoting isneeded.(write obj)Writes a single object, obj, to thestandard out file.(display obj)Writes obj to the standard out filein a more readable format.(Strings aren’t quoted, andcharacters aren’t escaped.)(newline)Forces a new line on standard outfile.170CS 538 Spring 2008© PortsPorts are Scheme objects thatinterface with systems files. I/O tofiles is normally done through aport object bound to a systemfile.(open-input-file "path to file")This returns an input portassociated with the "path tofile" string (which is systemdependent). A run-time error issignalled if "path to file"specifies an illegal or inaccessiblefile.(read port)Reads a single Scheme object (anatom, string, vector or list) fromport, which must be an inputport object.171CS 538 Spring 2008©(eof-object? obj)When the end of an input file isreached, a special eof-object isreturned. eof-object? testswhether an object is this specialend-of-file marker.(open-output-file "path to file")This returns an output portassociated with the "path tofile" string (which is systemdependent). A run-time error issignalled if "path to file"specifies an illegal or inaccessiblefile.(write obj port)Writes a single object, obj, to theoutput port specified by port.172CS 538 Spring 2008©(display obj port)Writes obj to the output portspecified by port. display uses amore readable format than writedoes. (Strings aren’t quoted, andcharacters aren’t escaped.)(close-input-port port)This closes the input portspecified by port.(close-output-port port)This closes the output portspecified by port.173CS 538 Spring 2008©Example—Reading & Echoing aFileWe will iterate through a file,reading and echoing its contents.We need a good way to doiteration; recursion is neithernatural nor efficient here.Scheme provides a nicegeneralization of the letexpression that is similar to C’sfor loop.(let X ( (id1 val1) (id2 val2) ... ) ... (X v1 v2 ...))A name for the let (X in theexample) is provided. As usual,val1 is evaluated and bound toid1, val2 is evaluated and boundto id2, etc. In the body of the let,the let may be “called” (using its174CS 538 Spring 2008©name) with a fresh set of valuesfor the let variables. Thus (X v1v2 ...) starts the next iterationof the let with id1 bound to v1,id2, bound to v2, etc.The calls look like recursion, butthey are implemented as loopiterations.For example, in(let loop ( (x 1) (sum 0) ) (if (<= x 10) (loop (+ x 1) (+ sum x))sum ))we sum the values of x from 1 to10.Compare it tofor (x=1,sum=0; x <= 10; sum+=x,x+=1) {}175CS 538 Spring 2008©Now a function to read and echo afile is straightforward:(define (echo filename) (let ((p (open-input-file filename))) (let loop ( (obj (read p))) (if (eof-object? obj) #t ;normal termination (begin (write obj) (newline) (loop (read p)) ) ) ) ))176CS 538 Spring 2008©We can create an alternative toecho that uses(call-with-input-file filename function)This function opens filename,creates an input port from it, andthen calls function with thatport as an argument:(define (echo2 filename) (call-with-input-file filename (lambda(port)(let loop ( (obj (read port))) (if (eof-object? obj) #t (begin (write obj) (newline) (loop (read port)) ) ) ) )) )177CS 538 Spring 2008©Control Flow in SchemeNormally, Scheme’s control flow issimple and recursive:• The first argument is evaluated toget a function.• Remaining arguments areevaluated to get actual parameters.• Actual parameters are bound to thefunction’s formal parameters.• The functions’ body is evaluated toobtain the value of the functioncall.This approach routinely leads todeeply nested expressionevaluation.178CS 538 Spring 2008©As an example, consider a simplefunction that multiplies a list ofintegers:(define (*list L) (if (null? L) 1 (* (car L)(*list (cdr L))) ))The call (*list '(1 2 3 4 5))expands to(* 1 (* 2 (* 3 (* 4 (* 5 1)))))But,what if we get clever and decideto improve this function by notingthat if 0 appears anywhere in listL, the product must be 0?179CS 538 Spring 2008©Let’s try(define (*list0 L) (cond ((null? L) 1) ((= 0 (car L)) 0) (else (* (car L) (*list0 (cdr L)))) ))This helps a bit—we never gopast a zero in L, but we stillunnecessarily do a sequence ofpending multiplies, all of whichmust yield zero!Can we escape from a sequenceof nested calls once we knowthey’re unnecessary?180CS 538 Spring 2008©ExceptionsIn languages like Java, astatement may throw anexception that’s caught by anenclosing exception handler.Code between the statement thatthrows the exception and thehandler that catches it isabandoned.Let’s solve the problem ofavoiding multiplication of zero inJava, using its exceptionmechanism:class Node { int val; Node next;}class Zero extends Throwable{};181CS 538 Spring 2008©int


View Full Document

UW-Madison COMPSCI 538 - Equality Checking in Scheme

Download Equality Checking in Scheme
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Equality Checking in Scheme and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Equality Checking in Scheme 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?