daimous
daimous

Reputation:

Get first and last atom of a list and append them

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 append it at the end so that my output would be something like this:

(c 4 m z z n 6 d)

Any help will be greatly appreciated!

Upvotes: 2

Views: 303

Answers (2)

Timothy Pratley
Timothy Pratley

Reputation: 10662

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

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 what implementation suits best.

Upvotes: 1

Gordon Seidoh Worley
Gordon Seidoh Worley

Reputation: 8068

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

  1. Create two lists out of the existing one
  2. Put the two new lists together when the input list is empty, reversing the second list before putting them together.

So you should expect the function call to look like:

(myFunc inputList forwardList willBeBackwardList)

and when inputList is empty you want to do something like

(append forwardList (reverse willBeBackwardList))

(exact built-in function names will vary by the lisp you're using).

Upvotes: 0

Related Questions