1

I have a program that requires having a series of interchangeable functions.

In c++ I can do a simple typedef statement. Then I can call upon on a function in that list with function[variable]. How can I do this in Common Lisp?

sds
  • 58,617
  • 29
  • 161
  • 278
  • you can put lambda in hash-table, no need to define anything. then you can `funcall` it. – rsm Jul 19 '19 at 21:24
  • it would be nice if you added a (pseudo)code sample. – sds Jul 19 '19 at 21:28
  • 2
    I was sure in next 5 minutes some sds, sylwester or barmar would come and post 3 screens long answer that will again teach me something :) – rsm Jul 19 '19 at 21:39

3 Answers3

4

In Common Lisp everything is a object value, functions included. (lambda (x) (* x x)) returns a function value. The value is the address where the function resides or something similar so just having it in a list, vector og hash you can fetch that value and call it. Here is an example using lists:

;; this creates a normal function in the function namespace in the current package
(defun sub (a b)
  (- a b))

;; this creates a function object bound to a variable
(defparameter *hyp* (lambda (a b) (sqrt (+ (* a a) (* b b)))))

;; this creates a lookup list of functions to call
(defparameter *funs* 
  (list (function +) ; a standard function object can be fetched by name with function
        #'sub        ; same as function, just shorter syntax
        *hyp*))      ; variable *hyp* evaluates to a function

;; call one of the functions (*hyp*)
(funcall (third *funs*) 
         3
         4)
; ==> 5

;; map over all the functions in the list with `3` and `4` as arguments
(mapcar (lambda (fun)
          (funcall fun 3 4))
        *funs*)
; ==> (7 -1 5)
Sylwester
  • 47,942
  • 4
  • 47
  • 79
2

A vector of functions, where we take one and call it:

CL-USER 1 > (funcall (aref (vector (lambda (x) (+ x 42))
                                   (lambda (x) (* x 42))
                                   (lambda (x) (expt x 42)))
                           1)
                     24)
1008
Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
2

The already given answers having provided plenty of code, I'd like to complement with a bit of theory. An important distinction among languages is whether or not they treat functions as first-class citizens. When they do, they are said to support first-class functions. Common Lisp does, C and C++ don't. Therefore, Common Lisp offers considerably greater latitude than C/C++ in the use of functions. In particular (see other answers for code), one creates arrays of functions in Common Lisp (through lambda-expressions) much in the same way as arrays of any other object. As for 'pointers' in Common Lisp, you may want to have a look here and here for a flavour of how things are done the Common Lisp way.

peter.cntr
  • 308
  • 2
  • 8