This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2021-03-04
Channels
- # announcements (4)
- # asami (38)
- # babashka (20)
- # beginners (188)
- # cider (1)
- # clara (11)
- # clj-kondo (103)
- # clj-together (1)
- # cljs-dev (15)
- # clojure (138)
- # clojure-australia (5)
- # clojure-europe (33)
- # clojure-france (1)
- # clojure-losangeles (5)
- # clojure-nl (4)
- # clojure-norway (11)
- # clojure-serbia (3)
- # clojure-uk (11)
- # clojurescript (45)
- # community-development (3)
- # conjure (22)
- # core-async (18)
- # datomic (44)
- # defnpodcast (4)
- # deps-new (1)
- # depstar (49)
- # events (2)
- # fulcro (33)
- # girouette (2)
- # honeysql (37)
- # jackdaw (5)
- # jobs-discuss (16)
- # kaocha (3)
- # leiningen (4)
- # lsp (77)
- # malli (55)
- # membrane (4)
- # off-topic (61)
- # polylith (5)
- # quil (5)
- # reagent (33)
- # reitit (12)
- # remote-jobs (1)
- # reveal (4)
- # rewrite-clj (2)
- # sci (16)
- # shadow-cljs (22)
- # sql (1)
- # test-check (27)
- # tools-deps (44)
hi, there's much efficient method than this, but I'm stuck with this. any advice? the code is 1. creating a sequence of prime numbers 2. then pairs it 3. then calculate the gap/difference between pairs 4. if the condition met with the pairs' difference it'll return the 1st list of the pairs
(defn is-prime? [n]
(and (< 1 n)
(not (some #(= 0 (mod n %)) (range 2 n)))))
(defn prime-seq [from to]
(filter is-prime? (range from (inc to))))
(defn gap [g m n]
(first (remove nil?
(for [i (vec (partition 2 1 (prime-seq m n)))]
(if (= g (- (second i) (first i)))
i)))))
If the pair (3 5) meets the condition, you only want to return 3 or a list of the first elements of all pairs that meet the condition?
could the gap
function can be optimized more? to give quicker time processed?
the code I wrote, is already running okay, but i look for more efficient method
the result is to : return list of the first elements of all pairs that meet the condition
(defn gap [g m n]
(let [primes (prime-seq m n)]
(for [[m' n'] (map vector primes (next primes))
:when (= g (- n' m'))]
m')))
this is not an optimization, but a slight refactoring of the gap
functionHi, i got an error with this function
Syntax error (IllegalArgumentException) compiling recur at (*cider-repl 3. Clojure\Practice Learning:localhost:51246(clj)*:59:13).
Mismatched argument count to recur, expected: 2 args, got: 1
What i want to do is like this
(defn searchings
[y somevec]
(when (< y (count somevec))
(if (not (nil? (get somevec y)))
(get somevec y)
(recur (inc y)))))
so i can do something like this (searchings 0 [nil nil '(3 5) nil])
and return (3 5)
, how to modify the function?You need to recur with both arguments, currently you only provide y in your recursive call. You need to include somevec as well
(defn searchings
[y somevec]
(when (< y (count somevec))
(if (not (nil? (get somevec y)))
(get somevec y)
(recur (inc y) somevec))))
additionally, get
will return nil if nothing found, so you could shorten it further
@U01GQRC8W30: oooo okay noted.
@U11EL3P9U if-not
noted.. I'll try...
Thanks a lot!
(if (get somevec y))
(get somevec y)
(recur (inc y) somevec))
can further be shortened to:
(or (get somevec y) (recur (inc y) somevec))
I'm starting to read How to Design Programs and wanted to know how different is Scheme and Clojure. Can I use clojure to follow the book?
Not a Scheme expert, but I think quite different. Even though general good software principles are transferable from language to language, you might have a hard time following unless you know both languages quite well. If you really want to read the book, I would stick with Scheme for the time being. If you want to do Clojure, there’s probably better books out there to teach good Clojure program design.
Perhaps this comment by Rich Hickey is relevant to this discussion https://groups.google.com/g/clojure/c/jyOuJFukpmE/m/aZjWHBnsQ74J
Hi everyone, I've tried to solve this, and the code works fine, but it said execution time out 12000 ms which I should revise & made it more efficient. https://www.codewars.com/kata/561e9c843a2ef5a40c0000a4/train/clojure here's my code, any idea how to make this more efficient? I'm kinda stuck here.
(defn is-prime? [n]
(and (< 1 n)
(not (some #(= 0 (mod n %)) (range 2 n)))))
(defn prime-seq [from to]
(doall (filter is-prime? (range from (inc to)))))
(defn gap [g m n]
(first (remove nil?
(for [i (vec (partition 2 1 (prime-seq m n)))]
(if (= g (- (second i) (first i)))
i)))))
just remove doall from prime-seq function
i've tried that, same result, still time out
also algorithm is not really eficient I can recommend to read that article - https://www.thesoftwaresimpleton.com/blog/2015/02/07/primes
allrite will read that, and try it on... thank you for sharing
Your isprime is VERY slow. For a start you are checking its not a multiple of all the numbers from 2 to n, you only need to check up to the square root of n. You could also do a check if the number is even and if it is you can exit out early with false.
Maybe faster to generate all the primes under the limit for n, stick them in a set and check against that set when you need to?
Hello. I have a list of maps. Between these maps can have duplicate keys. And I need to "concat" the values of the maps with duplicated keys. List example: (def a '({"a" {"x" "xxx"}} {"b" {"y" "yyy"}} {"a" {"z" "zzz"}})) I need to transform it into: '({"a" {"x" "xxx" "z" "zzz"}} {"b" {"y" "yyy"}}) I'm trying to use "map" with "merge-with" to make it, but it generates a list-result with the same duplicated "a" key. Anyone can help-me?
Thanks, solved my problem!!
What’s a good way to use Clojure for scripting? What type of setup? My easiest way to start using the language in the real world is to make small file processing scripts. Right now I’m writing them in Cursive using a regular old project and running them with the repl but once I’m done I would like to use them as command line scripts I could eg pipe file content to etc. How do I go about that?
I've been writing command-line utilities for the last year or so at work -- dev-op kinda things. Lately, I'm a convert to babashka, but sometimes you're doing something a bit more complicated and it isn't yet supported in babashka, like using an internal, private lib or something. I do the following:
• Generate an uberjar
• Write a shell script that you can put on a path somewhere. It should basically just run java -jar <your-uberjar>.jar $@
(the last $@ thing just passes on the args).
We have a Homebrew repo at work that automates this for colleagues. They just have to run brew install <my-awesome-cli>
and the above steps are done for them. And they don't need to know they were written in Clojure...
I haven't yet done this yet, but presumably I should be able to write many of these in babashka now and just make bb
a dependency in my Homebrew formulas.
I'm barely conversant on babashka still, but on your next CLI, I would just try and see how far you get. For me, running the jar files was working well enough that I hadn't even glanced in babashka's direction. Plus my CLIs are somewhat chunky, so I still think that was the correct approach. For example, I wrote a CLI to query our hundreds of microservices to find those using a particular runtime environment or dependency. That involved combined several different APIs (internal and external) and the tooling for a full-blown Clojure JVM app is just better for that. But if I'm trying to do something that could almost be accomplished with a bash script, but where the script would get into dozens of lines, then I'll use babashka. Best bet: ask in #babashka about your particular use cases.
I’d estimate that a 500 line babashka CLI app is saving my team 1h per person per week, and I’ve put less then ~5 hours into the script in the last year. It’s a serious game changer.
@anders152 Here is an example: https://twitter.com/RameezKhanSA/status/1367378656679632897
#babashka for sure
Hi you lovely people. Does ayoone know: How do I add this library https://docs.datomic.com/on-prem/javadoc/datomic/Util.html to my classpath using Leiningen? I am basically going to use it to read edn-data from a file and turn it into a clojure data structure
lots of examples here too: https://grep.app/search?q=edn/read. You can browse to see how people use io/reader
in addition to the handy read-string
Hello! Just started learning about Clojure this past week. Quick question for anyone: I’m looking to find an example/project tutorial that walks through building an app that has a clojure backend and a clojurescript frontend
If you're just getting started, you might want to start with a small, purely Clojure web app using just the Ring and Compojure libraries before you also try to learn about ClojureScript tooling -- it is a bit overwhelming for some beginners, depending on their background.
There are no beginner-friendly frameworks in Clojure/Script like there are with many other languages. What are you familiar with @seb.wildwood?
With regards to programming in general, I’ve got years of experience in Python/JS/Go and newish experience with Elixir
What’s the best, minimal Clojure stack for a simple REST API that you’d recommend @seancorfield?
I recommend starting with Ring (for the web server abstraction) and Compojure (for routing), and then look at Hiccup (generating HTML from Clojure data) and/or Selmer (Django-style templating).
I often point beginners to this example project https://github.com/seancorfield/usermanager-example but the readme also links to an implementation that uses Reitit for routing (and Integrant instead of Component for managing the start/stop lifecycle of pieces of the app).
It's not intended as a step-by-step tutorial, but it is meant to be a well-commented example of what a small, server-side rendered, database-backed Clojure web app might look like.
I don't know what state this online book/tutorial is right now, but it might be a good place to look when you want to start exploring ClojureScript https://practicalli.github.io/clojurescript/ (be aware that the cljs world has a lot of options for how you build stuff). This will probably be helpful for (server-side) Clojure web apps: https://practicalli.github.io/clojure-webapps/
For REST, rather than HTML responses, you could look at compojure-api which builds on top of Compojure to focus on REST API features.
@jr0cket is usually very responsive if you have questions about his online books/tutorials (and he has a great deps.edn
file to learn from, for the Clojure CLI). There's also a #practicalli channel to dive deeper into his material.
Hey, I'm a noob. I'm trying to instantiate a class from a local Java jar. The jar is a package which contains more layers of packages, then of course classes.
I already added the path to the local jar in :resource-paths in project.clj
lein repl starts with no error, so I take that to mean the import statement is correct
When it comes to instantiate a class from the jar, that's where existing posts (from other forums) don't seem to be relevant
what import? adding to path is not importing and isn't an error if the path specified doesn't exist
I'm getting there
instantiating a class is just a question of using it, import is only a convenience so you don't have to type out the full name
classes are loaded when referenced
one class in the jar is called AccountValue
So in at the repl, I expect to be able to type:
are you trying to create an object of that class, or use a static method?
create an object
I didn't meant to interrupt, please do share what you tried and what the error was
Since the repl seems to know the names of things in the namespace, I figure I ought to be able to type 'A', tab
and then the repl will offer AccountValue as one of the options
But that is not happening
a repl won't do that
gotcha
because you haven't done anything that loads the class
ok how do i load the class
(foo.bar.AccountValue. arg1 arg2 ...)
(replace foo.bar with the real package, and figure out the args you need to the constructor)
or use (import foo.bar.AccountValue)
then (AccountValue. ...)
you'd need the import
before the "A" autocompletes
SUH WEET
Thank you man 🙂
hey guys, can anyone tell me how i can deal with a response after a POST request with the clj-http
package? i honestly can't find anything after googling
(defn translate [body]
(let [lang (body "language")
text (body "text")
resp (client/post watson
{:content-type :json
:body "{\"text\":[\"Hello, how are you today?\"],\"model_id\":\"en-es\"}"})]
resp))
(defroutes app-routes
(POST "/translate" {body :body}
(response (translate body))))
just getting the 500 stacktrace
the 500 is just the default ring/compojure 500
get requests work fine, and sending back some dummy data to postman in json is fine, but i'm not sure if client/post takes a callback or anything
posting the error will show whether the 500 is from your route doing something wrong, or a 500 from the endpoint that your route calls
alternatively put a try/catch around your call to translate and print any exceptions
very likely translate is throwing an error because whatever body is isn't callable as a function
another good thing to practice is separating the process of gathering input to a process (here an external call) and making the call itself consider making translate only return the argument to client/post
but back to the errors, they're not some annoyance from Java, they contain useful context
I am not (yet) sure from your description that you are drawing the right conclusion https://clojurians.slack.com/archives/C053AK3F9/p1614895507209200
ah, give me a moment
okay, sorry about that. i was using my API key wrong, and i've gotten it to work with postman; you're right -- the request was failing because i wasn't authenticated
(defn translate []
(let [resp
(client/post watson
{:content-type :json
:basic-auth ["apikey" apikey]
:body "{\"text\":[\"Hello, how are you today?\"],\"model_id\":\"en-es\"}"})]
(response resp)))
(defroutes app-routes
(POST "/translate" {body :body}
(translate)))
i've modified my code so that i'm not actually taking any request params or anything now, just sending a simple string to the API
my question still stands with how to get the response back. here's the stacktrace
it's important to structure your code so that you can bang on stuff while you write working dough vs. setting into motion a large Rube Goldberg machine by dropping a marble
yep 😛 very new to clojure still so..
in the stacktrace, it's clear that i'm binding the actual http client object to a variable
com.fasterxml.jackson.core.JsonGenerationException
Cannot JSON encode object of class: class org.apache.http.impl.client.InternalHttpClient: org.apache.http.impl.client.InternalHttpClient@2e20c4f7
the JSON generator appears to be trying to serialize the HTTP Client itself into the payload
ah, finally
(defn translate []
(let [resp
(client/post watson
{:content-type :json
:basic-auth ["apikey" apikey]
:body "{\"text\":[\"Hello, how are you today?\"],\"model_id\":\"en-es\"}"})]
(get resp :body)))
(defroutes app-routes
(POST "/translate" []
(response {:result (translate)}))
(route/not-found "<h1>Page not found</h1>"))
the response map being nil was the problem, i guess
yeah, still trying to figure out exactly why..
translate
used to return the whole response from clj-http -- but now you're picking out a particular piece of it (`:body`)
and sending the actual hash map for it to be valid json
I haven't looked at clj-http in a while, but there must have been some additional stuff being returned that the JSON serializer didn't know how to handle
{:result xxx}
ahh, i see what i was doing incorrectly
is this generally the way to deal with responses from post requests?
i'm so used to promises in javascript.. will execution halt until there is a success/failure?
there are options to provide a callback, or you can run it in a future
, or use a different lib
i asked the question initially because i honestly couldn't find anything saying that client/post may accept a callback
guess i didn't look hard enough
yeah clj-http is one of the oldest libs out there, it's accrued piecemeal design over time
i usually pride myself in my debugging, but learning clojure is kind of throwing me for a loop tbh
guess i'll take it slower
speaking of that, i actually wasn't able to get into my repl
it's super fun, much more productive than set up magic entry point that prearranges the world -> compile -> wait -> pray
so this is something i'm noticing with a lot of Clojure developers, even experienced ones
so, i run lein repl
and immediately get pages of errors
and i don't actually know how to load the namespace
you really don't want to use the terminal REPL (but still shouldn't have any stacktrace from it)
and there's a general truism, don't make loading namespaces do work. makes it close to impossible to not be able to get into a repl or require namespaces. this can often be why things break before you can get at them
I gotta run -- but there are hundreds of people here that can continue helping -- happy trails!
thanks so much @ghadi, really appreciate it 😄
@dpsutton i'll check my profiles file
this is my profiles.clj
{:user {:dependencies [[nrepl "0.8.3"]
[cljfmt "0.5.1"]]
:plugins [[cider/cider-nrepl "0.25.5"]
[lein-cljfmt "0.7.0"]]}}
not sure why i have both nrepl and cider-nrepl
i think i might have added it for vim functionality
removing the cider plugin seems to have solved that
excellent. if you need those back, there was an issue with that version of cider-nrepl. replacing it with "0.25.9" should fix it
hi, how can I turn this seq (\0 \0 \1 \1 \4 \0 \1 \7 \8 \0 \0 \1 \6) into a number 11401780016 ?
shortest path is probably (->> your-input (apply str) (Long/parseLong))
but usually if you have a seq of characters like that you started with a string, and that's something that can go to parseLong
I have this string “0011401780016X” and I would like to separate the last digit (which is always a letter) and the numbers to do some arithmetic operations
(let [input "0011401780016X"] (Long/parseLong (subs input 0 (dec (count input)))))
Got it with subs and nth