Get the first and last atom of the list and add them

Let's say I have this list

'((c d) (4 6) (m n) (z z)) 

      

How can I group the first and last element of each inner list and add it at the end so that my result is something like this:

(c 4 m z z n 6 d)

      

Any help would be greatly appreciated!

+2


source to share


2 answers


Here's one way in Clojure (which is a dialect of lisp):

user=> (def l '((c d) (4 6) (m n) (z z)) )
user=> (concat (map first l) (reverse (map second l)))
(c 4 m z z n 6 d)

      



Really depends on your problem as to which implementation is best suited.

+1


source


You need to create your list from two ends. I would suggest the following:

  • Create two lists from the existing one
  • Put two new lists together, when the input list is empty, flip the second list before merging them.

So, you should expect the function call to look like this:

(myFunc inputList forwardList willBeBackwardList)


and when inputList

empty you want to do something like

(append forwardList (reverse willBeBackwardList))

(the exact names of the built-in functions depend on the lisp used).

0


source







All Articles