Fork me on GitHub

Hello everyone! I’m starting to work with clojure, and I’m having some questions about project organization, I have a project with compojure and monger, how to you usually organize the files? How do I handle the database connection among the application? Do I have to connect on every request or do I connect on application start and reuse the connection?


@U8C850K42 When you're getting started, that's the simplest way (connect on each request) but for production apps you need to set up a connection, or a connection pool, at startup and reuse that as needed.


Component and Integrant are libraries that are intended for managing stateful things with start/stop lifecycles like connections, pools, etc.


There is some real application that I can check the code to see the best practices? Or some book that I can look into?


Clojure Applied is probably a good book for some "real world" advice.


(although it over-emphasizes records -- the author would rely less on them now)


The Clojure Cookbook might also be interesting to you.


You could look at the source of -- I hear that's quite well-structured (but I haven't looked at it myself). Nearly all the open source Clojure is libraries -- the apps are nearly all private.


Thank you very much Sean!


Clojure isn't very opinionated about structure, so you'll get lots of different suggestions about that of thing.


You said that the author would rely less on records now, what is the best practice today for modeling entities?


Plain ol' hash maps.


Data is the API. Entities are "just" data.


Following on from Sean's comment about Integrant, you might also be interested in This is a framework built on top of Integrant (by the same author) that pre-rolls a lot of common use scenarios into reusable modules - database connections and pooling being one. I'd suggest sticking to rolling your own for now though as that'll help you to appreciate what Duct adds on top more. I've worked on production systems using vanilla Integrant (+ aero for config) and systems using Duct and, whilst there's definitely a learning curve for Duct, I've found it worth the effort.

Carl Waerner00:01:48

Hello you all 🙂 I am JUST starting with clojure and i'm just doing a simple test to try and write to a .txt file: (defn write-to-file [] (`slurp "file.txt" "test123"))` (`write-to-file)` I get the error

(slurp "file.txt" "test123"))
       ^--- Use of undeclared Var tallex.time-dive/slurp
I'm probably missing something really obvious?


@carl.waerner How are you running that code? In a REPL? Where did tallex.time-dive come into that code?

Carl Waerner01:01:42

Hello Sean! @seancorfield I just saw that... sorry. I am following a tutorial and that's where the tallex.time-dive came in. I tried the same in the REPL and it gave the same error however!


In a fresh REPL:

$ clj
Clojure 1.10.1
user=> (defn write-to-file []
         (slurp "file.txt" "test123"))
user=> (write-to-file)
WARNING: (slurp f enc) is deprecated, use (slurp f :encoding enc).
Execution error (FileNotFoundException) at .FileInputStream/open0 (
file.txt (No such file or directory)


clojure.core/slurp reads from a file.


Do you have a link to this tutorial? Perhaps it's wrong/outdated?

Carl Waerner01:01:14

It's this one. But it's nothing wrong with the tutorial 🙂 I just wanted to try out stuff on my own

Carl Waerner01:01:42

Even if I do this one in a fresh REPL. I get "use of undeclared Var"


Ah, ClojureScript


slurp and spit are Clojure functions -- I don't think they exist in ClojureScript.

Carl Waerner01:01:26

I see...! My idea was to write to a .txt file to use as a super simple database 🙂


ClojureScript is intended to run in a browser or on Node.js. Clojure is intended to run on the JVM -- lots more file system and database stuff available there.


Clojure for the Brave and True is a good place to start, if you're really just getting started. Otherwise consider Living Clojure as a beginners' book.

👍 4

Or Getting Clojure, another good book to get started with.

😍 4
Carl Waerner22:01:37

Thank you, appreciate it! 🙂


hello, I am trying to take this code and do something similar in clojurescript:


but I have errors that clj-kondo can't resolve the symbols.


Also, I am not totally sure if I am requiring the correct libraries


@seancorfield I took your advice of trying to use spec instead of schema, but I would like to try to use the orchestra "defn-spec"


I've never looked at Orchestra.


(and I don't do anything with ClojureScript)


I had asked about this on reddit, and someone wrote this for me:


It seems to me like a nice way to putting the spec right into the function definition


I get the impression some sort of combined spec/defn thing is going to be part of Spec 2, based on what Alex has been saying. Rich is deep in thought about function specs for Spec 2. So I'm waiting until that drops since it'll be standard and built-in.


In the meantime, I'm sticking to plain Spec 1.


So, random morning thought. TypeScript, Python types on the rise... specs in Clojure. Is it a trend? For now? Will it pass? What does it say, if anything? :face_with_monocle:


That many developers are willing to spend a lot of time designing and implementing various kinds of type systems, both static and dynamic, for languages that originally did not have them?


Yes, seems like it. In the year 40000, a family of genes will be discovered that innately drives us to create ever more complex type systems. Until a prophet comes and declares that no, there is another way. And then the cycle repeats, forever.


(Compare this to the human tendency to sort, categorize and arrange by <all the attributes>. Type systems are just a more advanced symptom. 😄)

Jack Park15:01:24

Still, there are final causes for categorization :male-farmer:


@derpocious You can use a configuration to make errors around orchestra.core/defn-spec disappear. See last note here


I'm having a bit of difficultly understanding core.cache. What I'm trying to do appears very simple (in fact, just following the wiki), yet the results are not what I expect


(require '[clojure.core.cache :as cache])
(def C (cache/ttl-cache-factory {} :ttl 5000))
(-> C (assoc :a "Hello World"))
(:a C)


the result of evaluting (:a C) is nil.


pretty much a 1:1 from here


the structures are immutable

🎯 4

(def TTL-CACHE (cw/ttl-cache-factory {} :ttl 5000))

(defn expensive-rest-call
  (println "Sooopar expensive networky REST call")
  {:name "Foo" :surname "Bar"})

(defn get-data
  (cw/lookup-or-miss TTL-CACHE k expensive-rest-call))

(get-data :a)


That works as expected. First hit prints out the println on the repl, a few more hits does not, until the 5 seconds has expired.


Hi! I'm looking for something like maplist in Common Lisp:

(maplist (lambda (x) x) '(1 2 3 4))
→ ((1 2 3 4) (2 3 4) (3 4) (4))
Is there any clojure equivalent or should I just use loop with recur on (rest ...) ?


(take-while seq (iterate next ...))

👍 4

I had this (take-while #(not (empty? %)) (iterate rest my-list))


Thanks! my idea looked overcomplicated to me for something so simple 😉

Alex Miller (Clojure team)14:01:56

You might find reductions to be a useful tool here, maybe with pop

David Pham15:01:37

I would like to store a sample of the arguments and the image from functions that are called during a test run, such that I could run regression test afterwards. Is there a library that already provide such functionality? I am thinking of a non intrusive library (that is one that would perform alter-var-root

David Pham16:01:00

and wrap functions from some namespace with the right behavior?

David Pham16:01:37

The goal would be to log the arguments that are run during the program to make regression test during libraries updates.

Jakob Durstberger17:01:41

Hello 🙂 I am reading Programming Clojure and am following along the chapter on spec. I ran into a bit of a problem which I don't fully understand. Trying to execute the following code returns me a Runtime Exception Invalid token: ::music/id ...

(s/def ::music/id uuid?)
(s/def ::music/artist string?)
(s/def ::music/title string?)
(s/def ::music/date inst?)

(s/def ::music/release
  (s/keys :req [::music/id]
          :opt [::music/artist
Converting them to single colons work. I think the ones starting with :: are "qualified keys" but I am not exactly sure what that means and why that wouldn't work. Any help is much appreciated.


@jakob.durstberger it means auto -resolve the alias music so I wonder if you don't have a namespace required with that alias?

Jakob Durstberger17:01:16

@seancorfield yeah, I definitely don't have a namespace music. The book mentions auto-resolving namespaces a few pages earlier but I haven't fully understood them yet. At least now I know what I have to search for / re-read. Thank you 🙂

Alex Miller (Clojure team)18:01:12

This is a bug in the book - should either be : or define the alias

Alex Miller (Clojure team)18:01:13

There was a period in 1.9 pre releases where this did work and I think this code may have been checked during that time, then not checked at release time


Which would look more like "good" Clojure code?


Sometimes I think heavy use of threading compromises the readability, are both really fine? @alexmiller


I suspect the readability of a threading form is more related to how familiar the reader is with each of the functions/macros in the steps, than with the length. Also general recommendations like avoiding relying upon subtle details (or commenting those).


Thanks for the input @U0CMVHBL2, it's clearer now! Thank you @alexmiller as well!


Good threading macros read like a bullet list.


But if some intermediate function does a lot, and it gets difficult to read, you can use more and more of let to add names to the intermediate results in order to help the reader


@zignd They are not quite equivalent, I think? In the first one you have (apply (resolve-controller operation) operation) and in the second you have ((resolve-controller operation) operation) -- apply treats the last argument as a sequence (of arguments) in the call. Assuming the controller function takes a single argument, I think the first form would need (apply [operation]) so that the semantics match.


And that apply would make me want to use the second form instead.


Or I might use (as-> f (f operation)) instead of (apply [operation])


Would it be ok to use as-> only for this line?


You're correct @seancorfield! After a few iterations not understanding what was going wrong I realized I was not using apply correctly. But thanks for noticing that and telling me xD


(let [operation (adapters/from-json-to-map line)]
    (-> operation
      (apply [operation])


This is the current state of that code xD


(-> line
    (as-> op ((resolve-controller op) op))
another possibility 🙂


Would it be ok to use as-> only for this line?


That indeed looks pretty :thinking_face:


Yes, as-> is designed to be used in a -> pipeline to provide a binding, to be used in an expression where the item being threaded is neither the first argument nor the last argument.


Interesting! I'm going to change to that! Thanks @seancorfield!


You can also put ->> into a -> pipeline for any subset that needs to be "last argument" as opposed to "first argument" threaded, but some people consider that a code smell and an indication that you're switching between thing/collection and sequence so you should refactor into smaller functions.


(there are lots of good pieces of advice in that blog series -- although not all of them are considered universally good style in Clojure)


Nice! I'll make sure to read them, might enlighten me in new possibilities with the threading macro. This one you showed me with the as-> is really clever tho, I don't that would come to my mind hahahah


To give you an idea of usage, we have 32 instances of as-> in 19 files, out of a 90,000 line codebase.