unsurewalnut
unsurewalnut

Reputation: 9

In Clojure, Can You Add an Item to a Second to Last List?

 (defn my-function
   [all]                   ; Assume all = '((I am) (A Fan) (Of) Yours)
 )

Is there a way to take the last element of all (which is Yours) and store it into the second to last collection so that:

 user->          (my-function '((I am) (A Fan) (of) Yours)  )
 Output ->       ((I am) (A Fan) (Of Yours)

I am unsure if there is any specific built-in function. Here is some psuedocode to what I'm thinking:

 (defn my-function
   [all]                   

  (cons (last input) (second to last input)

 )

Assume input all could be of any length with any variables.

Upvotes: 0

Views: 232

Answers (1)

Zac Romero
Zac Romero

Reputation: 406

Using a combination of drop-last take-last and concat you can implement my-function as follows:

(defn my-function [all]
  (let [start (drop-last 2 all)      ; start=(I am) (A Fan)
        [a b] (take-last 2 all)      ; a=(of) b=Yours
        new-end (concat a (list b))] ; new-end=(of Yours)
    (concat start (list new-end))))

Upvotes: 2

Related Questions