Search code examples
clojurelispcommon-lisp

How to pass "applied function" as a parameter in Common Lisp


I am new to Common Lisp, and am trying to implement a repeatedly from Clojure. For example

(repeatedly 5 #(rand-int 11))

This will collect 5 (rand-int 11) calls, and return a list: (10 1 3 0 2)

Currently, this is what I'm doing:

(defun repeatedly (n f args)
  (loop for x from 1 to n
       collect (apply f args)))

Which doesn't look as nice, I have to call it like this: (repeatedly 5 #'random '(11)). Is there a way to make the function more intuitive, as in Clojure's syntax?

The code can then get pretty ugly: (repeatedly 5 #'function (list (- x 1))).

https://clojuredocs.org/clojure.core/repeatedly


Solution

  • I'm not sure if I understand your question correctly, but maybe just something like this:

    (defun repeatedly (n function)
      (loop repeat n collect (funcall function)))
    

    Since #(…) is just a shorthand for lambdas in Clojure.

    CL-USER> (repeatedly 5 (lambda () (random 11)))
    (0 8 3 6 2)
    

    But this is even a bit shorter:

    CL-USER> (loop repeat 5 collect (random 11))
    (5 4 6 2 3)