开发者

Finding element in list in Scheme

i'm very beginner of Scheme and try to figure out how it is functioning; so i want to write a basic code: first of all i have a definition set: zipcode (ZIPCODE CITY STATE)

(define zipcodes '(
 (96774 ookala hawaii)
 (90001开发者_开发问答 losangeles california)
 (90263 malibu california)
 (10044 newyork newyork)
 ))

i try to write a function that input is zipcode and return city and state name for example:

 >(find '10044)
 (list 'newyork 'newyork)

 >(find '99999)
 empty because there is not zipcode like that.

Thanks a lot...

I'm not allowed to us LET function


Use assoc

> (assoc 90001 zipcodes)
(90001 losangeles california)
> (cdr (assoc 90001 zipcodes))
(losangeles california)


(define filter
   (lambda (proc lst)
       (cond ((null? lst) '())
             ((proc (car lst)) (cons (car lst) (filter proc (cdr lst))))
             (else
                (filter proc (cdr lst))))))

(define find-zip
   (lambda (zip lst)
      (define match (filter (lambda (item) (= zip (car item))) lst))
      (if (null? match)
          '()
          (cdar match))))

(define (find zip)
    (find-zip zip zipcode))

I think that will work for you. Filter will apply its first argument (a procedure) to each item in its second argument, which needs to be a list. The first argument needs to return a boolean value for each item it's passed. Filter will then return a list with all of the items that returned true when the first argument was applied. Otherwise, it returns an empty list.

In this case, each item in the list you're passing is itself a list of 3 items, so it compares the first item in that list with the zip code you're looking for. If it's a match, it returns true. So if the zip code is in the list, it will return the three item sub-list. Then we check to see if we got an empty list, if so, then we return an empty list. Otherwise, we take the cdr of the car to get your desired city and state.


Well so you can basically just filter the list for the zip code, I have sketched some code below (I'd write it differently, except I don't know what you have available outside of what is defined in RnRS).

(define find-zip
  (lambda (zip codelist)
   (if (empty? codelist) empty
    (if (= zip (car (car codelist)) (list (cadr (car codelist)) (caddr (car codelist)))
        (find-zip zip (cdr codelist))))))

It would probably be better should you use a let, and I think most implementations have a filter function that let you do this better.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜