This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2017-06-13
Channels
- # beginners (78)
- # boot (27)
- # cider (13)
- # cljs-dev (41)
- # cljsrn (4)
- # clojure (216)
- # clojure-android (1)
- # clojure-conj (6)
- # clojure-greece (1)
- # clojure-italy (11)
- # clojure-russia (127)
- # clojure-spec (63)
- # clojure-uk (34)
- # clojurescript (68)
- # core-async (5)
- # cursive (5)
- # data-science (1)
- # datomic (4)
- # dirac (11)
- # editors (7)
- # events (1)
- # graphql (12)
- # hoplon (39)
- # jobs (1)
- # liberator (3)
- # lumo (101)
- # off-topic (14)
- # om (3)
- # onyx (3)
- # parinfer (14)
- # re-frame (10)
- # reagent (2)
- # remote-jobs (1)
- # ring-swagger (17)
- # sql (21)
- # untangled (38)
- # vim (3)
- # yada (23)
is there a lib that contains a function like template
in:
(template
":label must be a string between :min-length and :max-length characters"
{:value "First Name"
:label ""
:min-length 3
:max-length 100})
which returns "First Name must be a string between 3 and 100 characters"
?I guess you could start with plumatic/schema ? I don't know about the string parsing part though
but it's straightforward to give a data shape to schema and get back the parts that didn't match in a readable form
not that I've seen
oh wait - is this just a templating question? ugh, I totally misread it
@noisesmith yep. sorry
I thought you were asking for data validation with string parsing
not string inerpolating templates, lol
I can't seem to get rid of this error running lein repl
: Warning: cider-nrepl requires Clojure 1.7 or greater
I've tried deleting ~/.m2/ and I've verified with lein deps :tree
that I'm getting Clojure 1.8.0 (which I have as a manual dependency, not a transitive). Once the repl loads (clojure-version)
returns 1.8.0
, as expected.
sounds like a cider bug
how recent is your cider version?
@noisesmith I'm using cider-0.14.0
@devth there's cl-format https://clojuredocs.org/clojure.pprint/cl-format that can do all kinds of crazy stuff
how can you find the powerset of a set? I see two options:
(1) do it myself
(2) use combinatorics
, as recommended in https://stackoverflow.com/a/20914117. However, somewhere between version 0.0.7 of combinatorics and the present, subsets
lost the ability to operate on sets. To use the most recent version of the library, I’d have to transform my input from a set to something else.
Hey folks, I'm playing with Apache Beam which relies on overriding methods in a DoFn
class. Based on beam-clj
, I've got a Java class that resolves a var to an IFn to get around that but I'd like to pass in an anonymous IFn directly instead of having to define elsewhere and resolve it. When I pass an IFn directly, I get a ClassNotFoundException
for my anonymous IFn when Beam is trying to deserialize the class that contains it
What is different about the anonymous (fn...)
vs. a (defn...)
? I thought they both produced classes when compiled?
Or is it the clojure.java.api.Clojure.var("foo", "bar")
that's working the magic here?
@brabster if you aot a namespace the things in defn will become classes. anonymous functions are created at runtime so cannot have classes created for them ahead of time
Functions defined within a function are still compiled AOT, possibly with a Constructor parameter if they're Closures
ah that's interesting. til. I think for the purposes he's talking about it'll amount to the same thing though. he'll need the entire closure available an invocation time which can happen on different machines to creation
@brabster fwiw, we've been writing beam jobs in clojure for about 6 months now, and we've settled on DoFn's that load the required clojure code (if needed) at runtime and invoke the specified vars with any arguments needed. we do this by specifying either a var "`#'foo`" or a var with any extra (serializable) closure args as "`[#'foo :bar]`" which gets translated into a little bit of data like {:ns 'user :name 'foo :args [:bar]}
and gets invoked by the DoFn as (user/foo whatever beam params make sense in context :bar)
Nice, thanks chaps... @bfabry I reckon there's a nice blog post in what you've described there ;)
Has anyone in this chat already wrote his update-in-each
function, which acts like update-in but only if finds a seq - update-in-each’s all the elements? I found https://github.com/ctford/traversy but it’s not composable but links to haskel’s lenses, which makes me find http://funcool.github.io/lentes/latest/ but I don’t see anything abstract, which will focus any item in collection... so anyone sticks with own version of update-in-each?
@razum2um i think you're looking for https://github.com/nathanmarz/specter
nathanmarz: looks fine 👍 I’m talking about structure like this
(def ex {:x {:y [{:a {:b 1}} {:a {:b 2}}]}})
(update-in ex [:x :y] (fn [xs] (mapv #(update-in % [:a :b] inc) xs)))
if vec happes twice it gets even worse 😕with specter that's just (transform [:x :y ALL :a :b] inc ex)
if you have a particular example of input -> output I can show you how to do it
Is it still the case that if you extend-protocol to two interfaces and you call protocol methods on an object that's instance of both of them, you can't know which implementation you will get?
Is it possible that a Clojure function returns a mutable reference to a local variable to the caller?
@mahdix - Not exactly. The atom
function, for example, returns a reference to a mutable thing.
It kinda depends on what you mean by "local variable".
In Clojure (and Lisps in general) this is usually a let
binding, meaning the association of a name to a value.
The binding itself is immutable, although it can be shadowed by another binding for the same name to a new value.
So if you could return that binding, it wouldn't be mutable.
But then, returning the binding isn't really how it would work anyway. If you returned anything from the function, it'd almost certainly be the value of that binding.
And one of the possible values in Clojure is a mutable reference type, like an atom.
Does that help?
Thanks @jeff.terrell
What I am looking for is to know whether something like this is possible to happen in Clojure:
We call a function f
which starts a new thread/process and passes some data to it which is returned to us at the end as a mutable data.
@mahdix Yes. You can just return an atom
(defn f []
(let [a (atom nil)]
(future (Thread/sleep 1000) (reset a :done))
a)
More usually this is done with a promise
, which can only be written to once.
@weavejester if I call f
and modify it's output value, will it affect the a
which is used inside the thread? In other words, will calling f
result in shared mutable state?
If I’m understanding you right, yes, @mahdix
So for example:
(def f []
(let [a (atom nil)]
(future (Thread/sleep 10000) (println @a))
a))
That sleeps for 10 seconds, then prints the value held in a
user=> (def output (f))
user=> (reset! output "hello")
...
hello
So you can change the value after the function has returned.
I am trying to refactor a function that uses as->
(commented) to ->>
thread macro format for learning purposes. I got this far but I am getting an arity exception error. What am I missing?
;; (defn anagrams [word words]
;; (as-> words w
;; (string/lower-case w)
;; (map #(compare word %) words)
;; (.indexOf w (apply min w))
;; (get words w)))
(defn anagrams [word words]
(->> word
(string/lower-case)
(map #(compare word %) words))
(apply min)
(.indexOf)
(get words)))
joshjones: ->> is a form rewriting cosntruct, it doesn’t care that methods are not first class, method calls without function wrappers are allowed inside ->> / -> / as-> etc.
(as long as they end up in a method invocation position and not a value position in the resulting form)
I think (memfn indexOf)
would work too.
Still got an exception:
RuntimeException Unmatched delimiter: ) clojure.lang.Util.runtimeException (Util.java:221)
ArityException Wrong number of args (1) passed to: core/apply clojure.lang.AFn.throwArity (AFn.java:429)
Still doesn't give me back the same result as the commented code would though, still something is off.
This is what I am using by the way: https://repl.it/Ij2N/0
I am just trying to go over each element in a sequence; but when one condition is fulfilled, break the dorun
@rinaldi - Your map
line breaks the flow of ->>
, since it doesn't use the threaded value. Haven't thought about what you might be trying to do, but just noticed that the pattern didn't quite fit so thought I'd mention it.
rafaelrinaldi: I think you're tagging the wrong Jeff, FWIW. :-)
Is there a partition-all
function in core that also fills in the sequences that are too short with some value?
@jeff I thought about extracting that piece to its own function but couldn't come up with something that works
@urbank does this work for you?
> (partition 10 10 (repeat :pad) [1 2 3 4 5 6 7 8 9 10 11])
((1 2 3 4 5 6 7 8 9 10) (11 :pad :pad :pad :pad :pad :pad :pad :pad :pad))
I'm having trouble accessing a method from within a utility class. I do not know a great deal about utility classes in java. The class I'm trying to access the digamma method of org.apache.commons.math3.special.Gamma. For the documentation I cannot find any constructor of this class (docu here http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/index.html). When I try (new org.apache.commons.math3.special.Gamma) I get No matching ctor found for class org.apache.commons.math3.special.Gamma
@hiredman thanks for your response, I have tried (.digamma org.apache.commons.math3.special.Gamma 3.2) but I get No matching method found: digamma for class java.lang.Class
where 3.2 is an arbitrary double
is this the incorrect way to accesss a static method?
@michaellindon the syntax is (org.apache.commons.math3.special.Gamma/digamma 3.2)
ooh brilliant
that worked
thank you 🙂
@wiseman Oh, thats very cool! I wouldn't have thought of that... didn't know you could pass multiple arguments to partition. Thanks!
https://funcool.github.io/cuerdas/latest/#interpolate provides string interpolation, but the literal string must be provided at compile time (like in its examples). for example:
(let [value 1
e "foo ~{value}"]
(cstr/istr e))
returns "e"
but:
(let [value 1]
(cstr/istr "foo ~{value}"))
returns "foo 1"
.
is eval
the only way to work around this? (not sure this would even be a workaround. a bit confused on when macro expansion is happening and how or if i can delay it).@devth looks like that macro just delegates to a function -interpolate, so you could call that (it is private so there's no guarantee it will work across versions etc)
i guess the reason it needs to happen at compile time is because it captures outer scope
something like https://github.com/weavejester/comb
Hi, can we output test result in junit xml format with mvn test on clojure web app ?
clojure.test has a with-junit-output
macro you could hook up (I don’t know the details about hooking clojure.test up with maven though)
I haven’t tried this plugin but it claims to set this up for you https://github.com/talios/clojure-maven-plugin
Do you know some example I can refer to?
Do you know if there is a way to verify a set of client certificates against a CA cert? I mean,
I need to create in clojure a function that given a client certificate can show me if the certificate was issued by a CA,
For those curious, the solution for my as->
to ->>
problem that I posted earlier today was to split my chain into more functions: https://repl.it/IjtX/1
rafaelrinaldi: Great solution. Cheers!
i feel like i have a relatively vanilla project, but lein test
won’t run if i don’t have a network connection. is that expected?
[wiseman@Yoyodyne cca_intent_classifier (master)]$ lein test
Jun 13, 2017 1:45:57 PM org.apache.http.impl.execchain.RetryExec execute
INFO: I/O exception (java.net.SocketException) caught when processing request to {s}->https://clojars.org:443: Network is unreachable
@wiseman Do all other lein
commands run?
@captainlexington no. lein run
also fails. It complains about a jar that is not in clojars/maven, that i have installed locally using lein install
.
Could not transfer artifact com.xxxxx:xxxxx-java-client:pom:1.2.0 from/to central ( ): : unknown error
specifically, i have C depends on B depends on A. A is a separate java jar that B.project.clj uses by doing :repositories [["project" {:url "file:maven-repo" username "" :password ""}]]
Is it not possible to use records and/or types as atom values? Getting an odd error when I try to stick my trie record type into an atom
atoms can hold anything, and are reasonable for any immutable type
@kingmob what does the line of code putting the thing in the atom look like?
@noisesmith (atom (default-alphabet-trie-node 0))
where default-alphabet-trie-node is a factory fn
yeah, that would only fail if the call to default-alphabet-trie-node did
It’s not failing there
It’s failing on a @db
call
Trys to call deref-future instead of `(.deref ref)
those are the same thing
what’s the actual error
Unhandled java.lang.ClassCastException user.AlphabetTrieNode cannot be cast to java.util.concurrent.Future
core.clj: 2206 clojure.core/deref-future core.clj: 2228 clojure.core/deref core.clj: 2214 clojure.core/deref REPL: 79 user/process-op REPL: 73 user/process-op
so you aren’t derefing the atom, you are derefing the thing in it
deref tries a few things, finally trying to deref a future, so the error message is slightly misleading
Hmmm, the default-alphabet-trie-node fn is memoized…could that be related?
somewhere you replace your handle to the atom with the contents of it
perhaps by taking the value of swap!
OK, I am recurring with the db being in the loop bindings
sounds like the db shouldn’t be a loop binding if it’s an atom?
since you’d want the same thing for every recursion
(unless the loop were inside the function you pass to swap! of course)
Right, right, if it’s an atom, it doesn’t need to be rebound
@kingcode correcting what I said above - deref checks if something is a clojure IBlockingDeref instance, and if not it trys deref-future. So any object that doesn’t actually support deref will get an error message mentioning deref-future
Is there any way to destructure as a set? to check for keys as flags for example?
Like this for example? (defn useful [& #{:keys [print console window sound async]}] (when print (println "Hello, useful")))
Is there a better way to do what I'm thinking of using it for then? as the example?
That looks fine, but then the arguments will actually have to be passed in as a set, rather than simply being queried to see if keywords exist among the args. The desire would be to be able to call the function as (useful :print :console) rather than as (useful #{:print :console})
(defn useful [& args] (let [caps (set args)] ...))
Okay. thanks!
even for maps that style of destructuring is problematic and I would avoid it, better to pass the map
It’s a similar set of trade offs with unrolled keyword arguments vs passing an options hash map. Passing the set or map composes better but is slightly less convenient for humans to type.
(e.g., java.jdbc
used to be all based on unrolled keyword arguments but it was a bit of a pain to work with when building abstractions on top of it — so I made a breaking API change to accept a hash map of options instead: users have to type {
}
around their options now but composing the functions is so much easier)
Okay, so the general form of using the keyword arguments destructuring is generally considered bad practice then?
Or at least when having the user pass it in as separate forms rather than as an actual map?
https://dev.clojure.org/pages/diffpages.action?pageId=1573132&originalId=15237210
Yeah, I was just looking at that. All it says now about argument destructuring is: “Idiomatic code uses destructuring a lot. However, you should only destructure in the arg list if you want to communicate the substructure as part of the caller contract. Otherwise, destructure in a first-line let. Example: my snake code from the book fails this test, doing too much destructuring in arg lists.”
Maybe @alexmiller could comment on the motivation for removing that? https://dev.clojure.org/pages/diffpages.action?pageId=1573132&originalId=15237210
I wonder if it was more around the configuration being least variant and therefore coming first (in java.jdbc
the options are always the last argument)?
I removed it because I did not think it was good general advice
There are times when kwargs are good, times when maps are good, etc
That is ringing some bells… there was a discussion about human-facing functions vs composable machine-facing functions, wasn’t there? Was it here or on the mailing list?
After writing a lot of production code using unstructured keyword args ie (foo data :key 1 :key 2)
I would definitely advise against it, I won't do that again, instead passing an options map as first arg. Too much overhead when trying to restructure args, refactor, applying args from a list, etc
Are there any gotchas with using recur
in a protocol fn?
E.g.
(add-substring [n s]
(let [[c & cs] s]
(when c
(let [i (alpha-idx c)
child (children i)]
(when-not child
(set! children (assoc children i child)))
(recur child cs)))))
seems like it should work, but I get an error about mismatched num of args for recur(Ignore the set! I’m going for extreme performance here ofr a coding challenge)
Basically, it adds a string to a trie, and should recurse on the appropriate child, with the rest of the string…
But I get Mismatched argument count to recur, expected: 1 args, got: 2
Oh, is that documented anywhere?
I’m finding the type/record documentation worse than most of CLojure’s docs…
yeah the recur call you have there could be a different function requiring another whole stack
Ahh, because it’s polymorphic?
(or could be)
I am not sure where it is documented, it only exists for protocol/interface methods inline in a record/type
so the documentation could be with protocols, or with records or types, or some special place for just that overlap
Got it. Thanks!