What are the best methods for including parameters such as battery in function?

I recently wrote Lisp code. In particular, recursive functions that take some data and create the resulting data structure. Sometimes it seems that I need to pass two or three pieces of information to the next function call in addition to the data provided by the user. Lets call these batteries.

What is the best way to organize these interfaces for my code?

I am currently doing something like this:

(defun foo (user1 user2 &optional acc1 acc2 acc3)
    ;; do something
    (foo user1 user2 (cons x acc1) (cons y acc2) (cons z acc3)))

This works the way I would like, but I am worried that I really don't need to provide & optional parameters for the programmer.

I consider several approaches:

  • There is a wrapper function that the user can use that immediately calls the extended qualifier.

  • use labelsinside a function whose signature is short.

  • just start using loop and variables. However, I would rather not do this, as I would really like to wrap my head around recursion.

Thanks guys!

+3
source share
3 answers

If you want to write the idiomatic Common Lisp, I would recommend a loop and variables for iteration. The recursion is cool, but it's just one tool for Common Lisper. In addition, tail call exclusion is not guaranteed by the general Lisp specification.

, labels, , , , . .

+4

-, . lisp, , .

(define (fibonacci n)
  (let fib-accum ((a 0)
                  (b 1)
                  (n n))
    (if (< n 1)
        a
        (fib-accum b (+ a b) (- n 1)))))

let , let, .

+2

, . , .

I came to the use of what I consider appropriate. If I think that leaving batteries &optionalin the API may make sense to the user, I leave it. For example, in the reduce-like function , the battery can be used by the user to provide an initial value, otherwise I often rewrite it as a form loop, door iter(from the iteration library), if it makes sense to perceive it as such. Sometimes an auxiliary is used labels.

0
source

Source: https://habr.com/ru/post/1733360/


All Articles