Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

functions that can take anything as argument

I have a function that does something with whatever is passed to it, and returns a list based on that.

How would one go about processing and mashing whatever arguments are passed to it into one list that contains every value?

Also, the ' is bugging me, as it makes calling somefunction2 from within somefunction1 problematic. Is there a way around this? It would be useful in my case to have an overly generic function that can take more or less anything as an argument, even other functions.

Possible arguments to the function:

  • NIL (should be treated as 0)
  • a number
  • a list of numbers
  • an empty list (should be treated as 0)
  • several lists some of which may or may not contain NIL, numbers, or
  • even more lists

Basically, what I want:

(somefunction '() 1 2 3 4 '(1 2 3 4 ) '(1))

...should be merged/mashed into:

(0 1 2 3 4 1 2 3 4 1)

... before being processed

Note: this is a follow-up to this question

like image 395
Jarmund Avatar asked Sep 19 '25 09:09

Jarmund


1 Answers

This should do it:

(defun weird-flatten (a)
    (cond ((null a) (list 0))
          ((atom a) (list a))
          (t (mapcan #'weird-flatten a))))

(defun foo (&rest args) (weird-flatten args))

EDIT: Noticed you're trying to do this as a learning exercise, so I guess I should explain. The first function is a pretty basic recursion. The only odd thing about it is that it uses mapcan rather than mapcar, so the result is merged into a flat list rather than retaining the same shape as the argument (um...mapcar takes an n-ary function and n lists as arguments and applies the function to each element of the lists, returning the resulting sequence; not sure whether that's too basic for you).

The foo function is a bit special in that it takes a &rest arg. This means that you can pass any number of things in to the function and the symbol args will be bound to the list of all arguments passed.

Why do you need NILs to be treated as zeros, out of curiosity?

like image 164
Inaimathi Avatar answered Sep 22 '25 04:09

Inaimathi