简体   繁体   中英

Using a boolean function in scheme

I want to use "member" function like "eq", "null" etc. However, I do not know how can I fix it?

(define (member atm lst)
    (cond
        ((null? lst) #F)
        ((eq? atm (car lst)) #T)
        (else (member atm (cdr lst)))
    )
)

and where I used;

(define (duplicate-entries lst)
    (cond
        ((null? lst) #F)
        ((member? (car lst) (cdr lst))) #T)
        (else duplicate-entries (cdr lst))
    )
)

member? does not work, how can i fix it?

You have defined member function whereas you are using member? . Define member as member? ie (define (member? atm lst) ... )

Let's take a look at each procedure in turn, first member . Be aware that there's already a standard member function in Scheme, so it's a bad idea to define a new procedure with the same name. Here's what the existing member procedure does:

member locates the first element of lst that is equal? to v . If such an element exists, the tail of lst starting with that element is returned. Otherwise, the result is #f .

The above procedure uses equal? for testing and returns a value different to what you expect. Somewhat closer to the intended procedure, we have the standard memq function:

memq like member, but finds an element using eq?.

But again, the returned value is not what you expect. I suggest you define your procedure like this, noticing that we're using memq , and according to the convention, the name ends with a ? to indicate that this is a boolean procedure:

(define (member? atm lst)
  (if (memq atm lst) #t #f))

Now let's look at duplicate-entries . There are a couple of parenthesis problems (correctly indenting the code would have shown this), and there's a problem with the name of the membership procedure (your procedure is called member but you're invoking it as member? ). You either use the member? we just defined above, or use memq , both approaches will work fine in this case, because memq will return a non-false value if the element was found, and that will make the condition true:

(define (duplicate-entries lst)
  (cond ((null? lst) #f)
        ((member? (car lst) (cdr lst)) #t)
        (else (duplicate-entries (cdr lst)))))

Or this, which is the recommended way - there's no need to reinvent the wheel if an existing procedure does what you need:

(define (duplicate-entries lst)
  (cond ((null? lst) #f)
        ((memq (car lst) (cdr lst)) #t)
        (else (duplicate-entries (cdr lst)))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM