Skip to content

Instantly share code, notes, and snippets.

@PEZ
Last active January 10, 2024 09:00
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/327178a78d8d0b021a72c75b0876a225 to your computer and use it in GitHub Desktop.
Save PEZ/327178a78d8d0b021a72c75b0876a225 to your computer and use it in GitHub Desktop.
Nth Element – Rich 4Clojure Problem 21 – See: https://github.com/PEZ/rich4clojure
(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
Copy link

evedes commented Sep 10, 2021

(fn [seq el] (nth seq el))
or
#(nth %1 %2)

@AndrewNelis
Copy link

#(first (drop %2 %1))

@StanTheBear
Copy link

(fn [sq n-index]
(get (vec sq) n-index))

@dm9de
Copy link

dm9de commented Sep 22, 2023

(def nth' (fn [s n]
            (->> s
                (drop n)
                first)))

Copy link

ghost commented Oct 5, 2023

(fn [coll n]
          (loop [x coll
                 cnt 0]
            (if (= cnt n)
              (first x)
              (recur (rest x) (+ cnt 1)))))

@prakharmisra2
Copy link

(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