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)))))
(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
functionI saw today https://gist.github.com/holyjak/36c6284c047ffb7573e8a34399de27d8
What exactly is the desired output you are looking for?
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
Hi, 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))))
also, the idomatic way is to do (if-not ,,,)
additionally, get
will return nil if nothing found, so you could shorten it further
i.e., (if (get somevec y) ,,,)
@sebastian.veile: oooo okay noted.
@dharrigan if-not
noted.. I'll try...
Thanks a lot!
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?
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
(if (get somevec y))
(get somevec y)
(recur (inc y) somevec))
can further be shortened to:
(or (get somevec y) (recur (inc y) somevec))
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.
i've tried that, same result, still time out
Perhaps this comment by Rich Hickey is relevant to this discussion https://groups.google.com/g/clojure/c/jyOuJFukpmE/m/aZjWHBnsQ74J
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.
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?
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?
(apply merge-with into a)
should do it
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?
wouldn't babashka help?
babashka is designed for this use case
@anders152 Here is an example: https://twitter.com/RameezKhanSA/status/1367378656679632897
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.
#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
is you goal to read a local edn file and turn it into Clojure datastructures?
Yes exactly
Found this now: https://clojure.github.io/clojure/clojure.edn-api.html
yup. that's where i was going to point you
Letโs see if I can get it to work with IO now ๐
(clojure.edn/read-string (slurp "deps.edn"))
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
Will bb support packages from the โofficialโ channels?
<http://grep.app|grep.app>
is my go-to to find examples. How does a pushbackreader get constructed, etc
Will check it out โ Down the rabbit hole I go!
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.
Be sure to come up for air now and again
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.
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.
Thanks for the guidance! Much appreciated
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
np
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
okay
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 ๐
:partywombat:
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
what did you try @usixjad?
post what you evaluated, and what it evaluated to?
(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
post that
in a snippet, please
CMD-shift-enter
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
a 500 sounds like an error on the server side
are you logging stacktraces?
the 500 error that clj-http throws will likely include the stacktrace in the :body
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
then you can inspect that at the REPL to ensure it's legit
then... make the call
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..
what is the main error you see?
in the stacktrace, it's clear that i'm binding the actual http client object to a variable
nope
call (translate)
, then inspect your result
break the problem down
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
that's the main cause listed in the trace
the JSON generator appears to be trying to serialize the HTTP Client itself into the payload
I should be clearer: call (translate)
from within your REPL
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
great, but don't 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}
vs {:result whole-response-from-clj-http}
ahh, i see what i was doing incorrectly
is this generally the way to deal with responses from post requests?
maybe? depends on the http library being used
this is generally the way I debug any issue though
i'm so used to promises in javascript.. will execution halt until there is a success/failure?
break it down, evaluate in my editor, put it back together
correct, this library happens to be synchronous
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
when I started with Clojure, it took me about 6 months to "get it"
I was pretty new to programming at the time, and I had to unlearn all the OOisms
but yeah, working with the REPL like you're working dough
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
...not using the REPL
doing something like lein test
every time you save a file, etc.
so, i run lein repl
and immediately get pages of errors
and i don't actually know how to load the namespace
lol
post em in a snippet
don't give up ๐
which editor are you using?
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
you probably have an old cider/cider-nrepl in your ~/.lein/profiles.clj
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
or somehow you're getting cider related stuff into the project
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
ty @dpsutton
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
just beware of empty strings. subs can be brutal
Iโm performing a regex validation before I get to this point, thank you
reduce would be more fun
user=> (reduce (fn [n digit] (+ (* n 10) (Character/digit digit 10))) 0 '(\0 \0 \1 \1 \4 \0 \1 \7 \8 \0 \0 \1 \6))
11401780016
user=>