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
150 views
in Technique[技术] by (71.8m points)

lisp - How do I pass in a list of list into a function?

(defun square (n) (* n n))

(defun distance (a b)
    (let ( 
        (h (- (second b) (second a)))
        (w (- (first b) (first a))))

        (sqrt (+ (square h) (square w)))
        )
)
(defun helper-2 (head) 
    (if (null (first (rest head))))
        0
    (+ 
        (distance (car head) (first (rest head))) 
            (helper-2 (rest head))
    )

I have this code written. My question is how do I use the helper-2 method? I've tried

(helper-2 '((2 0) (4 0)))
(helper-2 '(2 0) '(4 0)) neither works. Could anyone help? Thanks. 
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Please cut and paste the code in my previous answer and use it verbatim. Here, you've actually made some changes to the code to make it incorrect: instead of your original one-armed if, you've made it even worse, a zero-armed if.

A correctly-formatted two-armed if expression looks like this (noting that expr1 and expr2 are supposed to be flush with (indented to the same level as) test):

(if test
    expr1
    expr2)

This means that if test evaluates to a truthy value (anything other than nil), then expr1 is evaluated, and its value is the value of the if expression; otherwise expr2 is used instead. In the code snippet I had, test is (null (first (rest list))), expr1 is 0, and expr2 is (+ (distance (car list) (first (rest list))) (helper-2 (rest list))).


The other nice thing about using my code snippet directly is that it's already formatted correctly for standard Lisp style, which makes it much more pleasant for other Lisp programmers to read.


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

...