Skip to content

Instantly share code, notes, and snippets.

@ericnormand
Created March 1, 2021 16:09
Show Gist options
  • Save ericnormand/7a5a50b37a6a01b200ca59bd42897c7b to your computer and use it in GitHub Desktop.
Save ericnormand/7a5a50b37a6a01b200ca59bd42897c7b to your computer and use it in GitHub Desktop.
416 PurelyFunctional.tv Newsletter

Index filter

Clojure already has a function called filter. You pass it a predicate and it calls the predicate on each element. But what it doesn't have is a function called filter-index that calls a predicate on the indexes of the sequence to decide what to keep.

Examples

(filter-index even? "abcdefg") ;=> (\a \c \e \g) (keep even-indexed elements)
(filter-index prime? "abcdefghijk") ;=> (\c \d \f \h) (keep prime-number indexes)

Thanks to this site for the challenge idea where it is considered Hard in Python. The problem has been modified from the original.

Please submit your solutions as comments on this gist.

@sim-f
Copy link

sim-f commented Apr 11, 2021

(defn index-tuples [coll]
  (loop [c 0
         rst coll
         acc []]
    (if (empty? rst)
      acc
      (recur (inc c)
             (drop 1 rst)
             (conj acc [c
                        (first rst)])))))

(defn filter-index [f coll]
  (->> coll
       index-tuples
       (filter (fn [[i _]] (f i)))
       (map second)))

@dlidstrom
Copy link

dlidstrom commented Jun 20, 2021

let filterIndex pred seq = // (int -> bool) -> seq<'a> -> seq<'a>
    seq // seq<'a>
    |> Seq.zip [ 1 .. Seq.length seq ] // seq<int * 'a>
    |> Seq.where (fst >> pred) // seq<int * 'a>
    |> Seq.map snd // seq<'a>

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