Fork me on GitHub

looking for some code-golf ideas: Input: vector and an item that is present in the vector output: 0-based index of that item one solution

(first (keep-indexed (fn [idx i] (when (= 'c i) idx)) '[a b c d]))


I'd just use loop.


reduce does a lot of work to use the fastest way to go through a collection, falling back to the naive first and rest. I’d probably use reduce and reduced to take advantage of all of that


thanks guys!


(let [needle 300000
      haystack (range 500000)
      find-seq (fn [thing coll] (first (keep-indexed (fn [idx x] (when (= thing x) idx)) coll)))
      find-reduce (fn [thing coll] (reduce (fn [idx x] (when (= thing x) (reduced idx))) coll))]
  (doseq [[style coll-fn] [[:vector vec]
                           [:array long-array]
                           [:seq seq]
                           [:lazy-seq #(filter identity %)]]]
    (println style)
    (println "find seq:")
    (time (find-seq needle (coll-fn haystack)))
    (println "find-reduced:")
    (time (find-reduce needle (coll-fn haystack)))))
find seq:
"Elapsed time: 22.897 msecs"
"Elapsed time: 29.1585 msecs"
find seq:
"Elapsed time: 29.998666 msecs"
"Elapsed time: 13.251959 msecs"
find seq:
"Elapsed time: 8.895417 msecs"
"Elapsed time: 22.358708 msecs"
find seq:
"Elapsed time: 12.185917 msecs"
"Elapsed time: 7.973875 msecs"


very cool @U11BV7MTK thanks for sharing. Here's 3 versions:

(defn find-index [c item]
  (loop [c c, i (first c), idx 0]
      (= i item) idx
      (nil? c) nil
      :else (recur (next c) (fnext c) (inc idx)))))

(defn find-index2 [c item]
  (let [cn (count c)]
    (reduce (fn [idx i]
              (if (= i item) 
                (reduced idx)
                (when-not (= (inc idx) cn) (inc idx))))
    0 c)))

(defn find-index3 [c item]
  (get (zipmap c (range (count c))) item))
this is for low-perf code - kinda like the map elegance


In the loop option, just use the idx variable. You don't need c and i if c is always a vector - just use nth.

👍 1

I was profiling because nth makes me quite nervous and it can be horrendously bad since it is O(n) on some collections. Use it only if you know that your collections are indexed


(the profiling code has not returned after 30seconds 🙂 I think i’m in “heat death” territory here lol


find seq:
"Elapsed time: 7.863042 msecs"
"Elapsed time: 5.276917 msecs"
"Elapsed time: 183715.408666 msecs"


oh wow 🙂


Yeah, hence my explicit mentioning of there being "always a vector". :)


for sure. just wanted to point out how catastrophic that can be if you don’t heed that valuable advice

👍 1

You could also call .indexOf? (If it's not an array) Or is interop not allowed in code golf? No idea what the performance of that would be like on a seq ;)


Actually, that's probably the best answer, if it's CLJ and not CLJS.


And it works on CLJS too, so never mind the last part. :)


where does .indexOf come from? is that java util collections method?


Yep, from List on CLJ and just seems to be there on CLJS.

🙏 1

Yeah nice solution @U0P0TMEFJ

👍 2

How come you’re optimizing for performance, @U11BV7MTK? Does “code golf” sometimes refer to how fast the code performs and not the length of the code?


Or just some additional fun? 🙂

Jacob Rosenzweig17:06:08

Are there any good edn formatting tools? I have some static test edn files I need to pretty indent.

Jacob Rosenzweig18:06:27

Great CLI tool. I’ll have to use it later


when starting a socket REPL with clojure -J-Dclojure.server.repl='{:port 5555 :accept clojure.core.server/repl}', the commands I send to the REPL by doing something like echo '3' | nc localhost 5555 get shown in the response, on the side where I send it. Is there any way to also make the REPL itself print out what was evaluated and the evaluation result?


@edward.partenie Maybe prepl is what you need?

clojure -J-Dclojure.server.repl='{:port 5555 :accept clojure.core.server/io-prepl}'
$ nc localhost 5555
(+ 1 2 3)
{:tag :ret, :val "6", :ns "user", :ms 39, :form "(+ 1 2 3)"}


hmm, not quite, I don't think - I basically want the same output from repl, but for it to be printed inside the actual REPL instance as well


like making the REPL echo out any command that is sent to it...


(binding [*out* ( System/out)] (prn :hello))


Something to keep in mind is those are two different repls


Running in the same process, but different repls


So there is no "actual REPL"


One repl has its input and output attached to the processes stdin and stdout, the other has its input and output attached to a tcp socket


how can I make it do this for every command I run, though? :thinking_face:



user=> (require '[ :as io])
user=> (set! *out* (io/writer System/out))


user=> (require '[ :as io])
user=> (set! *out* (io/writer System/out))
Execution error (IllegalStateException) at user/eval146 (REPL:1).
Can't change/establish root binding of: *out* with set


you must evaluate this in your socket repl


I'm not sure it totally works though, cause I'd want the result of the evaluation to be printed, not just what is outputted to stdout :thinking_face:


ok, well, what @U0NCTKEV8 said ;)


you could start a new clojure.main repl? (clojure.main/repl :eval (fn [f] (binding [out ( System/out)] (eval f))))


The reason I am being pedantic about the relationship between the repl's (they are peers) is because if you are building tooling, baking in faulty assumptions, like there is one "the repl" and it is using the processes stdin and stdout, at the bottom, it is going to be very annoying to dig yourself out of that hole later


yeah, that makes sense. I'll try to work around it a different way (by writing the result gotten from nc straight to my editor window (the one in yellow)) - thanks for the help everyone!


I would back up and ask about your higher level goal vs your strategy for achieving it


Sure - I am trying to make the editor I'm using work more nicely for REPL driven development. I've made a thing where if you highlight the selection and middle click, it does echo $selection | nc localhost 5555, and this works, but I don't get any indication of what was evaluated and the result of the evaluation is


In general the way editors implement that is not by starting a new repl


But by copying the text and sending it to the input of the existing repl


(there is some variation in this in editors, and some expose multiple slightly different forms of this thing)


a lot of existing tooling uses nrepl, which makes it somewhat easier to inject stuff in to the middle (because it is message rather than stream based) at a significant increase in complexity


> But by copying the text and sending it to the input of the existing repl Hmm, that gave me an idea for a much easier way of solving the whole thing. Thank you!


I think you solved this already, but for the precise behavior you ask for here, you could make a custom OutputStream *out* which writes both to the existing previous *out* and the *out* of the REPL inside the editor's TTY, then use that OutputStream for the socket REPL's *out*

Braden Shepherdson19:06:29

I'm struggling to find a good way to structure an index to some data. once built, the index is immutable, which is nice. it's also a nested hierarchy, and the keys in different subtrees can collide. but that's okay I can use nested maps. the nasty bit is that there are two keys for each value, at each level of the hierarchy. so I can't naively use update-in, or the nested values will diverge. I'm tempted to make the inner maps mutable, so whichever path through the keys is taken the final value is the same. is there a way to build such a nested structure with transients, or other mutable structures, and get Clojure maps out in the end? should I use mutable Java Map types? flatten the map to a single layer where the keys are vectors of the path, using every permutation of the keys all pointing at the same value?


When I encounter such issues, I immediately seek ways to normalize that data.

👍 1
Drew Verlee19:06:52

what does it mean to have "two keys for each value" you mean like {"a" "drew" "b" "drew"} where changes to "a" drew and "b" drew should be synced?

Braden Shepherdson20:06:34

I think normalizing is possible. instead of a big hierarchical tree, a forest, where the upper levels of the hierarchy map to IDs rather than holding the real entities.

Drew Verlee20:06:56

You should look at datascript, it provides normalization. I'm sure there are thinner solutions.