The object ___ is not applicable [duplicate]

醉酒当歌 提交于 2020-01-10 05:56:09

问题


Hi I'm writing something that grabs every third element after the first element. However I can't test the logic due to ";The object (a b c d e f g) is not applicable." The code is below, atom? checks if it's a list, listful is defined as an empty list.

(DEFINE (threes var)
    (if(atom? var)
        ((newline) (DISPLAY "Bad input")  ))
    (APPEND(listful (CAR var)))
    (if(> 3 (length var))
        (threes (cdddr(listful)))
        (listful))
)

Can anyone give me some tips? Here is how I'm calling the method in the Scheme environment.

>(threes (list1))
>(threes '(A B C D E F))

回答1:


An if can only have one expression as the consequent, and one as the alternative. If you need more than one you have to use a begin to enclose the sequence of expressions - surrounding the expressions with () won't work, and that's causing the error reported, because Scheme interprets () as function application. This would be the correct syntax:

(define (threes var)
  (if (atom? var)
      (begin
        (newline)
        (display "Bad input")))
  (append (listful (car var)))
  (if (> 3 (length var))
      (begin
        (threes (cdddr (listful)))
        (listful))))

… However, that's unlikely to work. What you want to do has been asked a couple of times in the last days, in particular here is my own previous answer:

(define (threes lst)
  (cond ((or (null? lst) (null? (cdr lst))) lst)
        ((null? (cdr (cdr lst))) (list (car lst)))
        (else (cons (car lst)
                    (threes (cdr (cdr (cdr lst))))))))

For example:

(threes '(a b c d e f g h i j k l m n o p))
=> '(a d g j m p)

See the original question for other ways to solve the problem, with detailed explanations.



来源:https://stackoverflow.com/questions/22976298/the-object-is-not-applicable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!