开发者

How to declare a variable inside a Scheme function?

Is it possible to do so? Let's say I want to get开发者_如何学JAVA the last element of a list, I would create a variable i = 0, and increment it until it equals to length. Any idea? An example would be greatly appreciated.

Thanks,


There are several ways to declare a variable; the cleanest one is let:

(let ((x some-expr))
  ; code block that uses x

But you don't need this to get the last element of a list. Just use recursion:

(define (last xs)
  (if (null? (cdr xs))
    (car xs)
    (last (cdr xs))))

Note: if you want, you can use a variable to cache cdr's result:

(define (last xs)
  (let ((tail (cdr xs)))
    (if (null? tail)
      (car xs)
      (last tail))))


Yes, it's possible to define local variables in scheme, either using let or define inside a function. Using set!, it's also possible to reassign a variable like you imagine.

That being said, you should probably not solve your problem this way. In Scheme it's generally good practice to avoid set! when you don't need to (and in this case you definitely don't need to). Further iterating over a list using indices is usually a bad idea as scheme's lists are linked lists and as such random access O(n) (making the last function as you want to implement it O(n^2)).

So a simple recursive implementation without indices would be more idiomatic and faster than what you're planning to do and as such preferable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜