Processing the last item specifically when repeating a sequence

I find that I often have to process the last element in a sequence in a special way when iterating over it. For example, take the built-in function interpose:

> (interpose ", " (range 4))

(0 ", " 1 ", " 2 ", " 3)

One way to think about it:

  • Take the first item, add ","
  • Take the second item, add ","
  • Take the third item, add ","
  • ...
  • Take the second for the last item, add ","
  • Take the last item and do nothing

I also found that I needed to do something special when creating a Mig layout using Seesaw. For example, let's say I want to build this:

+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| 4 | 5 | 6 |
+---+---+---+
| 7 | 8 | 9 |
+---+---+---+

(, ). , Mig "", :

  • "grow" - 1, 2, 4, 5, 7, 8, 9
  • ", " - 3, 6

, :

  • ""
  • ", "

" ".

, :

  • ? -, ?
  • , ?

, , , , . , "" ?

+3
3

. clojure ( LISP ) cons'd .

, - , (, ). clojure first rest, .

@Rafal interpose, ...

  • , ","
  • , ",", ...

clojure () :

(defn interpose [s]
    (cons (first s) (map #(str "," %) (rest s))))

core.clj interleave, , , + rest.

(?) .

+1

, "". , , .

, (.. ) ( ) . , (.. Take). , , count, , , . , sw1nn.

, , . count, ​​ .

(def buttons [\a \b \c \d \e \f \g \h \i])

(defn partition-nth-but
  [n b coll]
  (map
    (partial map second)                            ; remove index
    (partition-by
      #(and (integer? (/ (% 0) n)) (not= (% 0) b))  ; partition by index every nth but b
      (map-indexed (fn [i v] [(inc i) v]) coll))))  ; index coll offset 1 

=> (partition-nth-but 3 9 buttons)
((\a \b) (\c) (\d \e) (\f) (\g \h \i))

(def grow str)
(def grow-and-wrap (comp clojure.string/upper-case grow))

=> (map apply (cycle [grow grow-and-wrap]) (partition-nth-but 3 9 buttons))
("ab" "C" "de" "F" "ghi")

,

(defn every-but-nth
  [n rf nf]
  (concat (repeat (dec n) rf) (repeat 1 nf)))

=> (apply concat
     (every-but-nth 3
       (every-but-nth 3 "grow" "grow-and")
     (repeat 3 "grow")))
("grow" "grow" "grow-and" "grow" "grow" "grow-and" "grow" "grow" "grow")

=> (map
     #(% %2)
     (apply concat (every-but-nth
                     3
                     (every-but-nth 3 grow grow-and-wrap)
                     (repeat 3 grow)))
     buttons)
("a" "b" "C" "d" "e" "F" "g" "h" "i")
+1

, n, , - n-1. .

n-1 ( 8) , 3 6. n (9) .

. , , . , , , clojure.

0

All Articles