This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2017-03-29
Channels
- # beginners (24)
- # boot (6)
- # cider (22)
- # cljsjs (1)
- # cljsrn (12)
- # clojars (3)
- # clojure (170)
- # clojure-china (2)
- # clojure-dusseldorf (18)
- # clojure-finland (1)
- # clojure-italy (32)
- # clojure-nl (1)
- # clojure-russia (65)
- # clojure-sanfrancisco (1)
- # clojure-spec (21)
- # clojure-uk (46)
- # clojurescript (92)
- # clojutre (1)
- # clr (7)
- # cursive (7)
- # datomic (6)
- # dirac (49)
- # emacs (17)
- # events (1)
- # funcool (20)
- # hoplon (6)
- # job (1)
- # jobs (1)
- # keechma (2)
- # leiningen (6)
- # lumo (74)
- # off-topic (15)
- # om (7)
- # onyx (40)
- # overtone (4)
- # pedestal (8)
- # powderkeg (4)
- # proton (2)
- # protorepl (2)
- # re-frame (18)
- # reagent (24)
- # ring-swagger (3)
- # rum (15)
- # slack-help (1)
- # spacemacs (20)
- # uncomplicate (62)
- # unrepl (29)
- # untangled (10)
- # yada (10)
Is there a preferred, idiomatic way to convert a map to a flat array (ie. [:a 1 :b 2 :c 3]
)?
I can think of about 3 different ways to do it.
also, flatten is pretty much never the right answer
(and problems that really call for flatten are usually a symptom of a design problem elsewhere)
specifically flatten
Yeah, I was leaning towards cat
with into
, but I have this niggling memory of having read somewhere that converting maps to vecs with into
is not considered idiomatic.
Maybe that was just for the trivial case without any additional transformation, or maybe it was just a bad source.
Classname/staticField
is how you get it (from https://clojure.org/reference/java_interop)
haha, anyway ... https://clojure.org/reference/java_interop (set! (. Classname-symbol staticFieldName-symbol) expr)
@josh.freckleton partial
might be slightly helpful. Possibly its distant cousins ->
and ->>
, too. I think we don't have arity functions like you want because they're easy to write--as you have done.
is it possible for a function in clojure to do different things based on the types of its arguments, in a general sense?
but what i mean is the general case of different types per argument and different numbers of arguments
for instance, if you had a function foo
that could take 2 strings, 1 int and 1 string or 1 string and 1 int, and each of these overloads does something different, how would you implement it?
bcbradley: not that this is the right way, but basically dispatch by mapping type over your arguments https://github.com/untangled-web/untangled-spec/blob/develop/src/untangled_spec/contains.cljc
hrm, is there a way to do it efficiently? (protocol dispatches on the type of the first arg in constant time, regardless of the number of types)
@branch14 Looks weird, but dispatching with identity feels wrong in the first place.
Why identity, and not say type?
@adambros This is an example. I'm dispatching on identity
to keep the the example simple.
Sure but you could use the instance from the arguments, and dispatch based on that it's a C
Well but surely there's a dispatch for telling them apart
Other than equality?
Actually that's a weird one, what does it use... What kind of equality is it doing, and are vars/pointers messing that up
That might be, I can try to find one, but that would be a work around for the issue I'm facing, which I haven't fully understood yet. đ
Essentially, you should be able to tell two instances apart, or they'd be the same
But I could see cases, like regex, where it's hard to tell if they capture the same strings
Hi, a question about package naming conventions and leiningen?
I notice that if my project.clj :main
definition refers to something like org.my-project.core, then leiningen fails finding my code when I try to run, even if I do have something like the following in my source files:
(ns org.my-project.core (:gen-class))
What should I know about the source directories hierarchy in clojure/leiningen project, to get around this?
Should the directory structure under src/ strictly mirror the namespaces which I declare?
matan: what's the file name, it should have underscores instead of dashes
Yes, which works for records and generally it works for vars declared up front. But it doesn't seem to work for records declared up front.
Well so why are you trying to use declare like this... Why isn't there a better dispatch function?
@matan lol was that it? You'd be surprised at how many times silly things can get the most experienced developers
Wouldn't worry about it
Just trying to fiddle an interleaving of Java â Clojure â Java leiningen compilation here đ
Ah yeah I've seen co-workers run into nightmare ish issues with that stuff
The reason to use declare and dispatching on record instances are beyond the example. I can find other ways and rewrite the code, but I was hoping that I just missed something.
Yeah I just feel it's wrong to declare a thing, dispatch based on identity, and then put an (complicated) object in that var...
For all I know, it could be holding on to the value of c when you defined the multi method
Thereby causing the problem you are seeing
I see, but wouldn't that be a general problem with dispatching on upfront declared vars?
but it feels mostly "right" when writing a library project that should be used from Java not only from clojure applications
@noisesmith Oh that's annoying, should I catch throwables instead?
@adambros thanks it was probably a mixture of uppercase and lowercase naming of source file names (a al Java) and clojure namespaces, close enough to your dash/underscore guess đ
Who maintains http://clojure.org ? Thereâs a broken link on the swag page (not broken, but it doesnât direct properly)
if i run a test with clojure.test/run-tests
, if a test fails, does it exit with 0
or 1
? the docs donât really say how it exits
is there any better we can do to read a properties file into a hashmap:?
(defn props [path]
(->> (doto (java.util.Properties.)
(.load ( path)))
(map (juxt #(.getKey %) #(.getValue %) ))
(into {})))
This is available in the propertied
library: https://github.com/michaelklishin/propertied
@m, seems like a decent solution already
@m, (-> (doto (java.util.Properties.) (.load (
đ
oh, or (into {} (doto (java.util.Properties.) (.load (
@m ^^
So much for sandwiching clojure between Java compilation steps? đ https://github.com/technomancy/leiningen/issues/847#issuecomment-290026580
@m, or (clojure.lang.PersistentHashMap/create (doto (java.util.Properties.) (.load (
đ
there's really no good way of doing that as classes can implement the underlying protocol interface (e.g. if you implement a protocol inline)
so from a tooling standpoint, this will need to be done from a textual starting point rather than a semantic point and using clojure itself?
@tbaldridge I had some time to think about what you said about breaking GL (and other) naming conventions with the lwjgl wrapper i was making, and after carefully considering it I think you are probably right. It'd be a shame to throw away all the work I've done, so maybe I'll make a json file out of the edn I extracted from the lwjgl javadocs and put it somewhere on a forum for people who might be interested in having it.
@qqq (into [] (.getAvailableFontFamilyNames (java.awt.GraphicsEnvironment/getLocalGraphicsEnvironment)))
the into call just gives you something thatâs readable in the repl in its printed form, if you plan on iterating on the result the into call is not needed
@noisesmith : thanks! I didn't realize getLocalGraphicsEnvironment was a static member function, which threw me off
I can fix the "Unable to resolve symbol: POne" by adding "(:import (rec_test2.protocols POne)" in ns function, but then I get ClassNotFoundException: rec_test2.protocols.POne. I tried requiring the namespace in various ways, and compiling the protocols file first, but nothing has helped yet. Any ideas would be appreciated.
In your Leiningen project.clj, specify that you want to AOT-compile this file using the :aot
option. I think that something like that will help.
@poverholt be sure that you require the other ns too
just the import doesnât suffice
and no, this doesnât need aot
Those are the areas I am trying. No luck yet. :aot did not help. I have both the require for the ns and import for the protocol symbol itself. No luck there either. Do I need the gen-class in the protocol's namespace?
no, you donât need gen-class
can you share the code for the namespace that attempts to use POne?
Any best practices for Component/Integrant, like where to define the components and how to name integrant keys?
Does the clojure.core.cache/ttl actually evict values and drop them from memory ones the ttl expires, or does it simply respin once queried?
laujensen it doesnât even know how to mutate your store (I use it with an immutable cache object, and use the cache function to swap! it)
it canât evict until a query happens (unless you have a timer running to swap! on it periodically I guessâŚ)
@poverholt minimal working example
justin@S: /tmp/proto-example$ cat src/example/a.clj
(ns example.a)
(defprotocol Aproto
(foo [this])
(bar [this]))
justin@S: /tmp/proto-example$ cat src/example/b.clj
(ns example.b
(:require [example.a :as a]))
(defrecord Brecord []
a/Aproto
(foo [this] :one)
(bar [this] :two))
justin@S: /tmp/proto-example$
justin@S: /tmp/proto-example$ cat src/example/c.clj
(ns example.c
(:require [example.a :as a]
[example.b :as b]))
(defn -main
[& args]
(println (a/foo (b/->Brecord))))
justin@S: /tmp/proto-example$ java -cp ~/bin/clojure.jar:src clojure.main -m example.c
:one
literally wrote and ran this just now
@poverholt lines 21 and 22 in test2.core need to namespace qualify the method calls
eg. proto/a
and you donât need to use import
@noisesmith It works! Thank you. The primary problem was NoClassFoundException and removing all gen-class seems to have fixed that. In the end, our team will compile all code, but that is a problem for another day. Thanks again.
@poverholt why are you compiling the code?
thereâs valid reasons to never do so, is why I ask
@noisesmith We have never deployed source code and I expect we would have to jump through hoops with our lawyers before we could do so. It's not impossible, just not likely. What are the concerns?
aot tends to break things in unpredictable ways, protocols in particular
itâs manageable (especially with the help of stuartsierra/component and clojure.tools.namespace/refresh) - but itâs a big hassle and itâs nice to avoid it altogether if you can
but if you have a reason to not deploy source, that makes sense
one nice trick for aot on deploy but never having it break things during dev (which is when it really tends to be a hassle), is to create a shim namespace that only uses clojure.core, and none of your other code. Inside that namespace (which uses gen-class) you have a -main that calls require at runtime and then uses resolve to find your real main and run it
@noisesmith Thanks. I'll check out the links.
as long as you never use the shim namespace during dev (and you donât need to) you can avoid a lot of the aot related dev time problems
is there a better/more composable way of saying: âif function applied to a value returns true, return the value, otherwise nilâ? Having to wrap whole thing in a lambda doesnât look great, e.g: (#(if (.isValid %) %))
, you can use this in threading macros and with comp
but Iâm wondering if thereâs nicer way?
i need to connect to a redshfit database and Iâd like to use HugSQL, what should my db map look like?
@ag with specter it's just (select-first some-pred? some-val)
@nathanmarz nice, but weâre not using specter yet (not in all our projects)
(and (f x) x)
(when (f x) x) ; if you prefer nil to false
oh, if the literal value true
is important, yeah
(when (true? (f x)) x) - if you need nil if not literally a true
just curious, why is this a macro?
otherwise method invocations would need to be wrapped in an anonymous function or memfn. Consider the function-based definition:
(defn when-pred-fn [f x] (when (true? (f x)) x))
(when-pred .isEmpty "a")
to
(when-pred-fn .isEmpty "a")
In the when-pred-fn
case, it'll throw, and you'll need to say something like:
(when-pred-fn #(.isEmpty %) "a")
or
(when-pred-fn (memfn isEmpty) "a")
sigh. I just want to do something like this:
(some-> v js/moment (#(when (.isValid %) %))
itâs clojurescript (but thatâs irrelevant). I thought thereâs nicer way, but seems lambda is unavoidable@mobileink howâs that different? You still need lambda
@quaeledyn filter complicates it even more - you canât âfilterâ single value - have to wrap it in a list, then return very first value
though (comp first (partial filter f) list)
has a certain point-free charm, as a definition
I think it just makes sense to have fn like this:
(defn some-val
[val pred-fn]
(when (pred-fn val) val))
@ag the definition of when-pred I provided basically is some-val as a macro. It doesn't need to be a macro I guess.
oh - a method call is a reason to use a macro maybe
you could definitely take something passed as a "function", determine if it's a symbol, and if it is, and it starts with a period, interpret that as an interop call
which would be a valid way to use a macro, although probably a bit too magical for my personal taste
btw. can someone tell me is there equivalent in clojure of Haskellâs flip
? Function that flips first two arguments?
thatâs not haskellâs flip @quaeledyn Iâve used this:
(defn flip [f]
(fn
([] (f))
([x] (f x))
([x y] (f y x))
([x y z] (f z y x))
([a b c d] (f d c b a))
([a b c d & rst]
((comp (partial apply f)
#(concat % [d c b a])
reverse)
rst))))
but most of that is just to be faster at smaller arities, essentially the code is just
(defn flip [f] (fn [& args] ((comp (partial apply f) reverse) args)))
although it looks like im fudging the definition of âhaskellâs flipâ by supporting more than flip :: (a -> b -> c) -> b -> a -> c
potentially where i âborrowedâ this from: https://gist.github.com/micmarsh/bcbe19c9de8bb7a471bf
I think I get it, so given a function, if it takes two or more arguments, return an equivalent function where the first two are swapped? so (f [a b]) -> (f [b a])
?
(defmacro flop
"create a version of a function with a modified arity as specified by a
vector of zero-indexed positions, e.g. [0 3 1 2]"
[f positions]
(let [syms (vec (repeatedly (count positions) gensym))]
`(fn [~@syms] (~f ~@(map syms positions)))))
I think this should work, though I haven't tested:
(defn flip [f]
(fn [& args]
(->> ((juxt second first nnext) args)
flatten
(filter identity)
(apply f))))
Tested now:
user=> ((flip -) 6 9)
3
user=> ((flip -) 6 9 2)
1
user=> ((flip -) 6 9 2 1)
0
e.g.
(some-> 1 (as-> n (if (even? n) n)))
nil
(some-> 2 (as-> n (if (even? n) n)))
2
@quaeledyn oh, yeah, I guess I forgot about as->
defmacro ->?, passing the output of expressions but the input of predicates that eval true?