Exercise 2
Write athat takes an item x, a stream s and a compare operator less-than-or-equal. The compare operator should work like the mathematical <= operator in comparing items in the stream. You may assume that the items in the stream are ordered so that if item a1 precedes item a2 in the stream s, then (less-than-or-equal a1 a2) is true. The member$ function is looking for an item y such that (less-than-or-equal x y) and (less-than-or-equal y x) are both true.(define member$ (lambda (x s less-than-or-equal)
You may find some of the definitions in memberex.ss useful.
Your function should work as indicated by the following transcript.
You will notice that I have set up a file in this directory dict.txt as a stream. This is technically not quite right because it's not infinite. If you try to search for a word that's beyond the last word in the dictionary, it is ok for your function to fail because it's trying to read past end-of-file. Mine just sits there and stares back at you. So do not try to test words like "zzz" for membership. Do not spend time now trying to deal with end-of-file; this will be the topic of a later exercise.> (member$ 47 ints <=) #t > (member$ -21 ints <=) #f > (member$ 37.32 ints <=) #f > (member$ "rhys" words string<=?) #f > (reset-words) > (member$ "barack" words string<=?) #f > (reset-words) > (member$ "barrack" words string<=?) #t > (reset-words) > (member$ "president" words string<=?) #t > (reset-words) > (member$ "washington" words string<=?) #t > (reset-words) > (member$ "george" words string<=?) #t > (reset-words) > (member$ "gwu" words string<=?) #f
You have to reset the words stream each time because a side-effect is involved in the member$ function. Each time you do a cdr$ you are performing a non-repeatable (read). Thus, when you have finished with the word stream you should reset it so it can begin reading at the beginning of the file again.
No comments:
Post a Comment