每个子列表中的最后一个元素

时间:2016-01-10 22:13:50

标签: lisp

我想找到最后一个数字原子(在任何级别)为奇数的任何级别的子列表数。 例如:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_SINGLE_PICTURE) {
            Uri selectedImageUri = data.getData();
            int myviewid = data.getIntExtra("myviewid",-1);
            Log.i("##MYLOG###", "###imageid:" + myviewid);
            try {
                Bitmap pic =  new  UserPicture(selectedImageUri, getContentResolver()).getBitmap();
                ImageView image = (ImageView) NewJobActivity.this.findViewById(myviewid);
                image.setImageBitmap(pic);
            }

答案应为3.(D 1(9 F)),(9 F),(G 7)。

我的代码:

 '(A (B 2) (1 C 4) (D 1(9 F)) ((G 7) 6))

问题在于验证功能。如果我执行

(DEFUN numara (l)
  (COND  
   ((atom l) 0)
   ((verif l) (+ 1 (apply '+ (mapcar #'numara l))))
   (t (apply '+ (mapcar #'numara l)))
  )
 )

(DEFUN transform(l)
  (COND
   ((null l) nil)
   ((numberp (car l)) (cons (car l) (transform (cdr l))))
   ((atom (car l)) (transform (cdr l)))
   (t (append (transform (car l)) (transform (cdr l))))
  ) 
)

(DEFUN verif (l)
  (COND
  ((null (transform l)) nil)
  ((= 1(mod (reverse (transform l)) 2)) t)
  (t nil)
 )
)

它给了我一个错误,它说:

numara '(A (B 2) (1 C 4) (D 1(9 F)) ((G 7) 6))

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

解决问题的一种更简单的方法是:

(defun last-numeric (list)
  "Return the last numeric element of a list."
  (find-if #'numberp list :from-end t))

(defun count-odd-last-numbers (list)
  "Recursively count all lists where the last numeric element is odd."
  (if (listp list)
    (let ((l-num (last-numeric list)))
      (+ (if (and l-num (oddp l-num))
             1 0)
         (loop for el in list
           sum (count-odd-last-numbers el))))
    0))

last-numeric使用find-if查找满足给定谓词#'numberp的列表的最后一个元素。 count-odd-last-numbers将检查参数是否为列表;如果没有返回0;如果是,请检查last-numeric是否返回奇数,并循环遍历所有元素,以递归方式调用它们并对结果求和。

作为对您的一般建议,您不应在Lisp代码中的单独行上使用结束括号。此外,在发布代码供其他人查看时,您应该尝试为您的函数和变量提供更具描述性,英语的名称。在Lisp中,你还可以在函数体中包含一个字符串(参见我的函数);这是一个docstring,它应该解释函数的用途。您可以使用(describe #'last-numeric)查看函数的docstring,也可以使用开发环境查看它(例如slime-describe-function)。

相关问题