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

Categories

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

Lambda function for optimization in Lisp

Consider the following function definition in Lisp:

(defun f (l)
    (cond
        ((null l) 0)
        ((> (f (car l)) 2) (+ (car l) (f (cdr l))))
        (T (f (car l)))
    )
)

Give a solution to avoid the double recursive call (f (car l)). You will not use set,setq,setf. Justify the answer.

This is how I proceeded:

(defun f2 (l)
    (cond
        ((null l) 0)
        ((lambda (x) 
           (cond
                ((> x 2) (+ (car l) (f2 (cdr l))))
                (T x)
           )
         ) (f2 (car l)) 
        )
    )
)

I want to hear some opinions. By the way, it's just an exercise. This function is not suposed to do something coherent.


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

1 Answer

0 votes
by (71.8m points)

Here I tried to reformat your code in a Lisp way:

(defun f2 (l)
  (cond
    ((null l) 0)
    ((lambda (x)
       (> x 2)
       (+ (car l) (f (cdr l)))
       (T (f (car l))))
     (f (car l)))))

The use of lambda is fine to compute a value once and bind it to a variable, and it in fact you can merge the two last original cases of cond inside the lambda.

But, there are multiple problems which makes the code incorrect.

  • recursive calls should call f2, not f
  • you can't move the test clauses of the cond inside the lambda, this is not how the Lisp syntax works. You probably only need an if, but if missed a cond inside the lambda for the (> x 2) case.
  • inside the lambda, do not call (f2 (car l)) since the whole intent of using an intermediate function is to use the parameter x (this is about the (T (f (car l))) form which looks like a cond clause but is interpreted as a function call)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.7k users

...