This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2018-04-05
Channels
- # beginners (240)
- # boot (5)
- # cider (48)
- # clara (2)
- # cljs-dev (3)
- # cljsrn (66)
- # clojure (111)
- # clojure-denver (2)
- # clojure-italy (42)
- # clojure-nl (5)
- # clojure-spec (12)
- # clojure-uk (45)
- # clojurescript (138)
- # community-development (7)
- # core-async (8)
- # datomic (27)
- # emacs (21)
- # euroclojure (6)
- # figwheel (10)
- # fulcro (29)
- # graphql (5)
- # hoplon (3)
- # luminus (1)
- # lumo (7)
- # mount (4)
- # off-topic (13)
- # onyx (20)
- # parinfer (3)
- # pedestal (4)
- # precept (1)
- # proton (3)
- # re-frame (41)
- # reagent (3)
- # reitit (28)
- # ring-swagger (7)
- # shadow-cljs (88)
- # specter (1)
- # testing (10)
- # tools-deps (27)
- # vim (58)
Perhaps a silly question, but: is it "normal" for my Windows 7 machine to have two java.exe instances continuously taking 13% CPU due to running Clojure repls (that aren't doing anything)? I hadn't noticed that behavior in the past, when I was doing Clojure stuff fairly regularly (then took a break to work on other stuff) -- and "lein repl" hangs after the prompt, though REPLs within existing projects seem to work okay.
Can anyone here understand Common Lisp code? I'm wondering which iteration function to use for porting some code of mine.
(Can anyone really "understand" Common Lisp code? š) Maybe post a snippet of the code in question and see if someone can explain it?
This is the function in question -- a nested "do loop" that is accumulating the results of calling an effect function on each item if it passes through a filter function. https://github.com/mfiano/gamebox-dgen/blob/master/src/neighborhood.lisp#L187-L195
Just glancing at it, I think some variant of reduce
would be suitable for the affectedp
handling...?
I really have no idea. I'll look into that though. Thanks.
It does.
How might I go about debugging a non-terminating clojure instance? Iāve been experiencing an issue occasionally where I run lein midje
, thereās an exception during the tests, and the process just hangs. I donāt get this issue when running the tests via the REPL with (load-facts :all)
.
I have seriously fallen in love with Clojure and trying to promote its use here in Finland: https://medium.com/@kari.marttila/using-clojure-to-implement-a-web-service-server-53f62dca964f
hey guys, question here, Iām getting the nth not supported on this type: PersistentArrayMap All I want is to iterate through key/value. Maybe filter instead, but the same idea applies. Code:
(doseq [[k v] (seq my-hash-map)]
(prn (apply str k v)))
@denisgrebennicov you can iterate a map like this but are you sure the error is not inside the loop ? apply expects last argument to be a sequence
Thanks. The problem was that I was having an array of dicts, therefore I couldnāt iterate through key/value pairs. It didnāt make sense
As an aside, you don't need the apply
in this case @denisgrebennicov
A TCP server in clojure
A code snippet , s'il-vous-plaƮt ?
Can some explain why I get this error?
(defn dfs
[g nxs v]
(let [n (peek nxs)]
(cons n (dfs g (remove v (concat (pop nxs) (n g))) (conj v n)))))
(dfs {:a #{:a}} '(:a) #{})
=> clojure.lang.LazySeq cannot be cast to clojure.lang.IPersistentStack
For this problem, if you convert (remove v ...
to (filterv (complement v) ...
you can fix that but then hit an error regarding popping an empty vector
I give, what's the right way to do dfs where you need to keep the path? I feel I have done 4 slightly wrong versions
I searched online and found two implementations with issues to :)
i suppose im trying to understand if im supposed to be leveraging some concept like reduce here. but that doesnt seem right as im not iterating over a sequence. i have done dfs several ways in the past with python and dont recall gettting this tripped up. maybe because of how i was taught the alg
What is the recommended naming convention for a project? lein new app org.company.product
?
We normally name the project itself product
, but the namespace/directory structure is structured in the java way as above.
But take that as anecdote, I'm uncertain of any broader conventions.
Hi there, has anyone ever seen this error? And knows how to solve it?
Uncaught TypeError: Cannot read property 'ReactCurrentOwner' of undefined
@uayyagari our loop bindings should have the accumulator
and your recur should be like (recur (rest arr) (inc n))
run
(let [n 0]
(inc n)
n)
one of the pillars of clojure is immutable data, if you're not storing the value somewhere, it isn't mutating. Also some of the binding names can become confusing, try not to overload a local def with a binding of the same name
Oh!! so its incrementing n but not storing that value in n. Right?
yes. sticking another binding in loop to bind to that and then pass it to the recur is the clojure way to do it
you have to keep in mind the nature of immutability in pretty much all code you write
I had initially included the binding in the loop but I wanted to see why this wouldn't work.
Thanks a lot @theeternalpulse
true! I keep forgetting. I make the same mistake in python
actually scratch that
I think you still have to check, I think common lisp an empty list and nil are equivalent
FYI If you use next instead of rest you will get a nil when you run out of stuff.
Right, I know there are some guidelines of using one over the other, have to check
@theeternalpulse almost always use next
I think I've used rest
about twice in the past 7 years
ah. i use rest to name destructured arrays
the rest params, which is probably bad practice
is the space complexity of rest O(n) and that of next O(1) ?
Iāve been researching how to create routing APIs in my clojure services, and Iāve noticed there are a lot of libraries / frameworks that people use to accomplish this. Iāve seen Liberator
, Ring
which appears to have a lot of problems from the articles Iāve read, Compojure
, and Pedestal
. What is the best one to use? Which one overcomes the problems Ring
has?
Will: for routing you want to use compojure
or bidi
. Liberator is a library that helps implementing semantically correct http resources (caveat: author speaking). ring
is the api model all this is based on.
Pedestal uses an alternative (but compatible) abstraction to ring, and delivers routing and more libraries with it.
In my experience the most beginner friendly option is to use compojure and then look weather you want to use liberator for better apis
Thanks, Iāll try that! @ordnungswidrig
Is there a way to call something like rest on a collection and keep the collection type?
(rest (sorted-set :a :b))
;;=> #{:b}
Strange -- I get (:b)
as a result in my REPL. Maybe a different version of Clojure running?
Anyway, seems like, generally, aspects of types connoting invariants (like "in sorted order") would be dropped for arbitrary modifications to instances of those types. E.g. consider (cons :c (sorted-set :a :b))
.
But whether certain operations, such as rest
, that would preserve such invariants, should do so, is an interesting question. Ideally rest
would know as little as possible about the details of its argument; and the type system as little as possible about various operations that can be performed...but maybe an invariant's description could include some kind of special knowledge such as "removal of items does not violate the invariant".
sorry if that was confusing⦠what i wanted was something that returned a set. So my example is what i want, not what i get.
i get what you get.
@drewverlee Like this
(let [coll (sorted-set :a :b :c :d :e :f)]
(into (empty coll) (rest coll)))
;;=> #{:b :c :d :e :f}
Not sure if it'll work in all cases but...
because sets arenāt ordered
peek and pop are about insertion point (ordering) and sets donāt have a known insertion point (you can āaddā anywhere in a sorted set)
@uayyagari I think they next and rest are similar, O(1) or nearly so, they just behave differently with an empty seq.
@alexmiller i have the same question that bjr has. In what way is a sorted-set sorted? I assumed a sorted-set had a concept of an index to value mapping. Otherwise i donāt understand the meaning of the word. If not, then then maybe another question will clarify, whats the usefulness of a sorted-set?
set semantics but able to sequentially traverse in a sorted order
How do I achieve a āpolymorphicā behavior in a sense, that I have a protocol defined, by defprotocol and I want two distinct implementations of this protocol. Since in my case I donāt need any fields, defining a record with no fields sounds wrong. I was thinking that I can smhow have 2 different keywords which implement this protocol. But keywords in my case would be objects and not classes, therefore this approach wonāt work, right? To get the picture clearer, I have a protocol with methods, which should be called but have different implementations depending on if I run it in --dry-run mode or not. Ideas? Or am I thinking too much in OOP style and need to change my thinking? š
@denisgrebennicov if you donāt use state, you can use a deftype
instead
they can dispatch on a keyword, so you can have on method for :dry-run
and one for :default
Iām struggling to create an in memory h2
database for my tests in clojure
. I have a file that contains all the create table statements and another with all the insert statements. How would i build the database using the schema file and dump all the data from the files?
also, regarding OOP: polymorphism is very much a Clojure thing, but mutable state is not. OOP combines these two concepts into one, and clojure does not
@denisgrebennicov If you don't have any state associated with your polymorphic behavior I'd think a multimethod would be what you want.
I wouldnāt shy away from records and types ā it can be a lot more direct to (if dry-run (DryRunObj.) (RealObj.))
than to use multimethods. Maybe sketch each out and see which you find clearer.
if youāre doing that, why use records in the first place?
(if dry-run
(dry-run-fn)
(real-fn))
I have like 2 cases, when I call the protocol defined methods. I write a mini auto-approver tool for some dumb pull-requests we have, so it happens to be like this (if-let [error (validate-pr pr)] (handle-error error) (approve-pr pr)) and the approve-pr has same methods to call, but different imp depending on dry-run condition or not approve-pr goes through the same procedure, like 1) change-status 2) post-comment 3) merge-pr The dry-run methods should just log it to the stdout, whereby the real imp should do some work, in this case networking requests
I would go for records + protocols here, and pass the record as the first arg, eg (approve-pr client pr)
, (validate-pr client pr)
and have a RealClient
and DryRunClient
like @U060WQTSB mentioned above š

Thanks! But still creating a record with no fields, feels kinda wrong :thinking_face:
heh, I promise that soon you will have a situation where āoh, I need to pass credentials to the clientā or āoh, I want pass a log path to my dry runnerā, and then records will come in handy š
also, instead of a record with no fields, you can use a top-level (def foo (reify SomeProto ...))
- it has all the method-implementing stuff with none of the value carrying stuff
hmm ok dfs version 4.
(defn dfs
[g nxs v]
(let [n (peek nxs)
v (conj v n)]
(when n
(cons n (dfs g (filterv #(not (v %)) (concat (pop nxs) (n g))) v)))))
Iām curios if anyone has any suggestions. I feel like seeing the different ways depth first search can be done is fairly instructional. I think (not filterv) is odd, but i canāt seem to use remove as it produces a lazy listā¦also iām probably supposed to be using recur
in order to avoid stack overflows if the graph is to large.
remove produces a lazy list. Which i canāt call peek on. I think maybe i should try to keep everything as a list. That way i could add and remove from the front and possible keep using the lazy-seq.
š Hi everyone! Newby to Clojure(script) here. Is this where we should ask questions about exercises (on [exercism](http://exercism.io/exercises/clojure), e.g.) we might be having trouble with?
@loganpowell indeed it is, fire away! š
@schmee Sweet! Thank you š
I ran the tests from exercism (http://exercism.io/exercises/clojure/bob/readme) - one-by-one - on these and they worked fine, but when I ran lein test
I was getting some failures due to what seems as multiple conditions getting evaluated... Might I be doing something wrong?
@loganpowell: what does "multiple conditions being evaluated" mean?
It seems that when the tests run, multiple conditions are returning true rather than just the first that returns true (which is what I expected)
I recommend that you print the intermediate values and make sure that they are what you think they are
also (if x true false)
can usually be replaced with x
(your (empty? string) check)
@loganpowell: cond always stops at the first true condition
that's what I thought :thinking_face:
@schmee I tried them out one at a time and it worked
in the repl
@loganpowell: could it be that the first one that returns true isn't the one you want, and you need to reorder the clauses in cond?
hmm⦠when I copypaste the code into the repl I get this:
user=> (response-for "")
"Whatever."
Yep, that's what it should do
try it with a question mark in there
@schmee note that "string" is a list of strings, so it is only empty if you provide no args
right, that's how I read the requirements
are we reading the same test?
(deftest responds-to-silence
(is (= "Fine. Be that way!" (bob/response-for ""))))
I read silence as no args
so if it's an empty string it's "whatever." š
or "whatevs", which is my preferred slang š
@loganpowell: but in that case your code and the tests disagree about the spec
and you are asking why those tests fail right?
I guess you could rewrite the test if you are that strongly opinionated about it
So, I think the tests are failing due to multiple answers coming through, e.g.,
clj
FAIL in (responds-to-shouting-with-no-exclamation-mark) (bob_test.clj:34)
expected: (= "Whoa, chill out!" (bob/response-for "I HATE YOU"))
actual: (not (= "Whoa, chill out!" "Whatever."))
that's not what is happening
there's no such thing as multiple answers
you just don't provide a behavior that the test is checking for
so, here two conditions seem to be met returning 1) Whoa, chill out!
and 2) Whatever.
@loganpowell: that's not what that message means
@loganpowell: clojure.test shows you what is expected, and what it got instead
Am I mistaken to see the test is expecting "Whoa, chill out!" and is failing because it's getting: "Whoa, chill out!" "Whatever."
you are mistaken
it is saying it expected "Whoa, chill out!" and instead it got "Whatever."
You guys were so right and I so wrong, thank you for the guidance!
@loganpowell Youāre not the only one who finds that output initially confusing.
you got me curious. apparently there is a with-tap-output
in clojure.test.tap
. i havenāt tried it but that should be less utterly confusing and you could run the output through a TAP formatter like faucet
oh, sorry, that stuff is totally unrelated to the new thing in Clojure core, sorry ābout that š
In nodejs, when I'm losing the war on dependencies, I can go nuclear with "rm -rf node_modules". Is there a way to delete all the dependencies I've downloaded for a Leiningen project and start over?
@d4hines an important difference is that all the dependencies via lein / maven are immutable and versioned - if deleting a dep and then pulling it down again ever resulted in a different version, that would be a big system level failure
(nb. there are SNAPSHOT deps, but those are an abstraction over weird timestamped verions)
@noisesmith As I understand it, npm is immutable as well, in the sense that you can't upload two packages with the same name and version. I'm more concerned about when adding a dependency breaks your build.
Then ask for a different version, there's no unversioned deps so deleting never helps
(or remove the dep, which makes it no longer visible to the project)
A key difference is an "install" (thing is available because in disk), vs "config" (it's available because you specified you wanted it, explicitly)
lein doesn't use installs in normal usage, it has an on disk cache backing up configs
That said, feel free to remove the cache, it will all get downloaded anyway next time
Just saying that deleting the cache doesn't fix bugs unless something very rare and bad happened
@d4hines thereās a lot more state represented in a node_modules directory than in the .m2 repository. deleting the repository is more akin to doing a npm cache clean
in fact, the m2 repo doesn't contain state - it's a cache, it just contains the presence or absence of resources
Ooooh, I think I see. I guess the issues I'm used to dealing with are from breaking changes being released under a bugfix.
Thanks guys.
right, with lein (used properly) you never get a version change unless you ask for it, and if you do, the simple fix is to ask for the older version
you can treat the fact that things are on disk as a simple implementation detail allowing you to avoid downloading deps on every startup
So I have a project I forked, and a library I wrote. The project works fine out the box. It works when I add the dependencies to my project.clj and when I import the library in a namespace, but as soon as I call the library's code, the project breaks. Here's what baffles me though: when I stash the changes, run lein clean, and try to boot up the project, it still breaks. If the dependencies are immutable, what's going on?
If it helps, the root error looks like it's this: Caused by java.io.FileNotFoundException Could not locate figwheel_sidecar/system__init.class or figwheel_sidecar/system.clj on classpath.
@d4hines sounds like the figwheel plugin didn't get loaded properly?
So, on a whim, I deleted my profiles.clj file which I added to the project, and now it works!
note that plugins are not transitive like other deps are, so the top level project should be able to decide if figwheel is being used
wait, you added an extra project.clj?
the primary role of project.clj is to calculate dependencies, so a broken one will be the main reason things like this break, yes
no, I was trying to use environ to get configuration options to my library, and the lein-environ plugin requires a profiles.clj file in the root.
The profiles.clj is just a map of the options.
oh, profiles.clj, OK
yes, profiles.clj is merged into project.clj
and a broken profiles file cna break your project
lein-environ doesn't actually require profiles.clj - you can put dev config into project.clj and then provide deployment config via the command line
Right, but I was hoping to keep my credential info in my profiles.clj, so I didn't have to type it in every time. In that merging process, how deep does it go? I assumed it was entirely non-destructive, and that nothing would be lost, only clobbered if specified twice, but now I'm not sure.
different keys have different rules, some are clobbered, some are merged
:eval-in pprint can clear up that ambiguity though
(if you put that in your project.clj map it just pprints your project config instead of running any task, after calculating the effective config)
Aaah. So add that and run it with and without the profiles.clj, and see the difference?
exactly
or just run it with profiles.clj and see which part got clobbered even
Not sure I get that.
:eval-in pprint ends up showing a project config, after merging apropriate profiles (whether defined in project.clj or profiles.clj etc.) - you should usually be able to tell if something is missing or misconfigured
but sure, compare the pprint of two configs if that helps too
Oh, I see. Thank you!
given the error you showed, I would assume you are losing your plugins key (the one that pulled in the figwheel plugin)
That would make sense. Here's another, higher level question though: how should I handle these configuration details in general? I was having my library use environ, but if my the project it's used in doesn't use environ, suddenly that seems less useful. Should I have the config be a parameter to every function? Or should I require the user to pass the config to a function that stores it in an atom for the other functions to use?
@d4hines a common pattern is to use a state management library (like component, integrant, or mount) and it can use environ or whatever else as part of creating the initial app state
I wouldn't put things into an atom unless they are a) shared globally and b) subject to arbitrary change at runtime from multiple threads
injecting configuration is much safer and makes testing and reasoning about behavior simpler
which implies that your library should not read values out of environ directly in the general case, but you could have a special āconfigure this thing from the environment for meā constructor that uses some standard environment variables youāve picked
I actually wrote a library to make tracking env access and variable definitions easier to manage after we wrestled with this in our services: https://github.com/amperity/envoy
That's really cool. I'm a bit confused about the "constructor" though. My end user can hand the options/object to the constructor function, but where does the constructor put them if not in an atom?
Or var of some sort.
@d4hines you pass them to something that uses them
this is the way component, integrant, mount, etc. generally work - you give them a thing, they figure out who needs it, and they create some state holding object and pass it to the relevant consumers as they start up their own state
there are many advantages to avoiding the globals (in terms of testing, growing the system in unexpected ways, etc.) - though mount actually does use global singletons if you end up preferring that style of state management anyway (I don't recommend it)
I really appreciate ya'll patience, but I'm still missing something. I have an api key k
and a function that consumes it f
. You're not saying to pass k
directly to f
, right? f
instead references k
, which is some sort of stateful object. So I use Component or Integrant to ensure that when f
references k
, it's defined appropriately?
@d4hines the initial startup of your application is all functions
one of these functions gets your api key as an argument, and passes it to the things it in turn runs (if they need it)
why would your api key be stateful?
and sure, if you need a stateful resource, you pass the container holding the resource as an argument to the thing that consumes it
as I said, it's possible to use globals instead, but explicit args are much more flexible and forgiving as designs change, and simplify testing
this reduces coupling between consuming and providing code
Ok, I think I get it now. I was trying to store the config once, but using the Component system, every function called by the user needs to accept the config as an argument. That should be fairly easy to do. Thanks again @noisesmith, and @greg316
@d4hines usually what this looks like is passing the relevant configs to your http server startup, so that the handlers that need it can be passed the api auth etc. or passing the configs to your db component so that it can use them to create a connection pool which is then passed to each function using the db etc. etc.
component plays well with the idea of protocols (as your abstraction interface) and records (as your implementation)
for example, you could create a protocol describing the operations you need to perform on a database (create a foo, list foos, delete a foo)
and yeah, you end up with a record whose keys hold a hash-map containing all the stateful objects that are needed (based on start up declaration) by this code context
and provide a real implementation as a record which extends the protocol - the record would have an attribute to hold the stateful connection or API auth or what have you
but your other logic just uses the protocol methods and doesnāt need to know whatās going on under the hood
I'm not sure why *print-length*
is not being honored in my project.clj dev profile. I set it to 5 as a test, and evaluating *print-length*
in the REPL says it's 100. Any ideas how to actually override this?
which also lets you do things like swap out a mock implementation for testing that might just stick your foos in an atom
@greg316, @noisesmith Can you recommend an example I could study?
e.g. https://github.com/greglook/blocks/blob/develop/src/blocks/store.clj#L15 (the protocol) vs https://github.com/greglook/blocks/tree/develop/src/blocks/store (the implementations)
so for example the S3 implementation is a record which internally maintains an S3 client with appropriate auth: https://github.com/greglook/blocks-s3/blob/develop/src/blocks/store/s3.clj#L214
@d4hines See if this complete web application example helps https://github.com/framework-one/fw1-clj/blob/master/examples/usermanager/main.clj
It has a WebServer
component and an Application
component, and ensures the application is added to the Ring req
uest so each handler can access it.
(it doesn't use a component for the DB connection -- because it lets the JDBC library create/close a connection on each call -- but it could be refactored to do that with a connection pool inside a component, that the application would "depend on")
Thanks @seancorfield. So... is a protocol+record combo any different than an interface/class?
It's similar. Clojure has both interfaces and protocols.
which is impossible in straight Java - imagine trying to make String implement a new interface. š
(which means, with Component, you can add a startup/shutdown lifecycle to arbitrary Java types š )
My experience in OO is with TypeScript, so my perspectives are probably all sorts of skewed. I think in TS I would just make a new interface implement the existing one, or have my new class extend the other existing one. Or am I missing the whole picture?