Last active
December 29, 2023 22:38
-
-
Save PEZ/bb564e188dc4d73aa37b714b64003dfe to your computer and use it in GitHub Desktop.
Penultimate Element – Rich 4Clojure Problem 20 – See: https://github.com/PEZ/rich4clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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! |
(fn [sq]
(get (vec sq) (dec (dec (count (vec sq))))))
(defn second2last
[coll]
(first (drop 1 (reverse coll))))
(def __
(fn [coll]
(-> coll
reverse
second)))
(def __ (comp second reverse))
(def second-last (comp first (partial drop 1) reverse))
I forgot about second
.
(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))))))
(def __ (comp second reverse))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
#(->> % reverse second)