Last active
January 10, 2024 09:00
-
-
Save PEZ/327178a78d8d0b021a72c75b0876a225 to your computer and use it in GitHub Desktop.
Nth Element – Rich 4Clojure Problem 21 – 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-021 | |
(:require [hyperfiddle.rcf :refer [tests]])) | |
;; = Nth Element = | |
;; By 4Clojure user: dbyrne | |
;; Difficulty: Easy | |
;; Tags: [seqs core-functions] | |
;; | |
;; Write a function which returns the Nth element from a | |
;; sequence. | |
(def restricted [nth]) | |
(def __ :tests-will-fail) | |
(comment | |
) | |
(tests | |
(__ '(4 5 6 7) 2) := 6 | |
(__ [:a :b :c] 0) := :a | |
(__ [1 2 3 4] 1) := 2 | |
(__ '([1 2] [3 4] [5 6]) 2) := [5 6]) | |
;; To participate, fork: | |
;; https://github.com/PEZ/rich4clojure | |
;; Post your solution below, please! |
evedes
commented
Sep 10, 2021
•
#(first (drop %2 %1))
(fn [sq n-index]
(get (vec sq) n-index))
(def nth' (fn [s n]
(->> s
(drop n)
first)))
(fn [coll n]
(loop [x coll
cnt 0]
(if (= cnt n)
(first x)
(recur (rest x) (+ cnt 1)))))
(defn n-th-1 [coll n]
(def ans (n-th coll n 0))
ans)
(defn n-th [coll n c]
(if (== c n)
(first coll)
(recur (rest coll) n (inc c)))
)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment