Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

Why the below lisp code is not giving desired result

I have a list

'((1 2 (A B C)) (2 3 (B C D)) (4 5 (C D F)))

I want to process the elements in the inner list, (in this case, I want to change (A B C) and other lists to (M M M)).

I wrote a code (process lst), which will do this task for the inner list.

(defun process (lst)
  (cond
    ((null lst) '())
    (T (cons 'M (process (cdr last))))))

And when I call from the main function,

(defun iterate-list (lst)
  (cond
    ((null lst) '())
    ((listp (car lst)) 
     (cons (process (car lst)) 
           (iterate-list (cdr lst))))
    (T 
     (cons (car lst) 
           (iterate-list (cdr lst))))))

I am getting ((M M M) (M M M) (M M M)) instead of ((1 2 (M M M)) (2 3 (M M M)) (4 5 (M M M))).

But when I use the same function, with just (cons (car lst)) (iterate-list (cdr lst))) in the second condition (listp (car lst)), I am getting the correct answer, that is

'((1 2 (A B C)) (2 3 (B C D)) (4 5 (C D F)))

I don't know where I am making the mistake.

question from:https://stackoverflow.com/questions/65896993/why-the-below-lisp-code-is-not-giving-desired-result

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

NB. You need to rename last to lst in process.

I am getting ((M M M) (M M M) (M M M)) instead of ((1 2 (M M M)) (2 3 (M M M)) (4 5 (M M M))).

The code works, but not that at the depth you want:

(process '(a b c d))
=> (M M M M)

(iterate-list '(1 2 (A B C)))
=> (1 2 (M M M))

In order to process all lists in your root list, you could do this:

(mapcar #'iterate-list '((1 2 (A B C))
                         (2 3 (B C D))
                         (4 5 (C D F))))

=> ((1 2 (M M M)) (2 3 (M M M)) (4 5 (M M M)))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...