Skip to content

Instantly share code, notes, and snippets.

@PEZ
Last active December 29, 2023 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PEZ/bb564e188dc4d73aa37b714b64003dfe to your computer and use it in GitHub Desktop.
Save PEZ/bb564e188dc4d73aa37b714b64003dfe to your computer and use it in GitHub Desktop.
Penultimate Element – Rich 4Clojure Problem 20 – See: https://github.com/PEZ/rich4clojure
(ns rich4clojure.easy.problem-020
(:require [hyperfiddle.rcf :refer [tests]]))
;; = Penultimate Element =
;; By 4Clojure user: dbyrne
;; Difficulty: Easy
;; Tags: [seqs]
;;
;; Write a function which returns the second to last
;; element from a sequence.
(def __ :tests-will-fail)
(comment
)
(tests
(__ (list 1 2 3 4 5)) := 4
(__ ["a" "b" "c"]) := "b"
(__ [[1 2] [3 4]]) := [1 2])
;; To participate, fork:
;; https://github.com/PEZ/rich4clojure
;; Post your solution below, please!
@evedes
Copy link

evedes commented Sep 10, 2021

#(->> %
    reverse
    second)

@StanTheBear
Copy link

(fn [sq]
(get (vec sq) (dec (dec (count (vec sq))))))

@ieugen
Copy link

ieugen commented Sep 28, 2022

(defn second2last
[coll]
(first (drop 1 (reverse coll))))

@esciafardini
Copy link

(def __
  (fn [coll]
    (-> coll
        reverse
        second)))

@joerter
Copy link

joerter commented Jan 28, 2023

(def __ (comp second reverse))

@dm9de
Copy link

dm9de commented Sep 22, 2023

(def second-last (comp first (partial drop 1) reverse))

I forgot about second.

Copy link

ghost commented Oct 5, 2023

(fn [coll]
            (loop [x coll
                   last-two-el []]
              (if (= (count x) 1)
                (first last-two-el)
                (recur (rest x) (conj (drop 1 last-two-el)  (first x))))))

@aaroncm
Copy link

aaroncm commented Dec 29, 2023

(def __ (comp second reverse))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment