Fork me on GitHub
#beginners
<
2020-05-03
>
Chris K00:05:04

Is it possible to have a variable inside regex? Like when I use re-matches, can I have like a variable from outside? Something like:

(def char-to-find \C)
(re-seq #"{char-to-find}" s)

Alex Miller (Clojure team)00:05:30

you can use re-pattern to make a pattern from a string

Alex Miller (Clojure team)00:05:06

and use format or whatever to make the string

Chris K00:05:23

but I want to loop with different characters to find

Chris K00:05:37

I need to count like character occurances in a string

andy.fingerhut01:05:40

If you want to count occurrences of individual characters in a string, is it within the entire string, or only a part matched by the regex?

Chris K06:05:31

like count characters in a string

Chris K06:05:53

I thought of other methods but maybe it's cause im bad, but I thought that regex would be the best

andy.fingerhut07:05:36

If you can be more specific about what kind of string you want as input, and what you want to count, that might help. If you want to count all characters in a string, i.e. its length in characters, that is just (count my-string) .

andy.fingerhut07:05:12

If you want to know how many times each different character occurs in a string, you can do (frequencies my-string)

Chris K07:05:59

yes! frequencies was what I was looking for thxs a lot

andy.fingerhut01:05:52

If it is in the entire string, then you don't need a regex to do that.

andy.fingerhut01:05:31

If it is in a single part, or several parts, of a string that match a regex, then I would recommend thinking about first finding those matching parts, then doing a pass over those matched strings that count how many times each character occurs in them, using a second function that doesn't use regexes.

andy.fingerhut01:05:55

Those are all efficiency concerns, not correctness, really, but maybe you are also concerned about efficiency.

andy.fingerhut01:05:24

If you need N different regexes, then dynamically generating N different regexes at run time, and matching a string against all N of them, should work correctly.

ScArcher02:05:27

How do you work with byte[] in Clojure? I'm using a library that gives me a byte[], offset, and length. I'm trying to get a string out of it and I'm not really sure what to do.

ScArcher02:05:47

I tried using subvec to get the bytes I care about out, but it doesn't seem to work with a byte[]

phronmophobic02:05:05

to convert from byte-array to clojure vector. you can do (vec my-byte-array)

phronmophobic02:05:23

to get a byte array from a vector, you can do (byte-array my-vec)

ScArcher03:05:50

Thanks for the help. I found an easier way to do what I wanted. (String. buffer offset length)

ScArcher03:05:51

I guess using Java's String is easier as it can create one from a byte array with an offset and length.

šŸ‘ 4
nick07:05:19

I was exploring various Ring middlewares and then found enduro > enduro provides a reference type similar toĀ http://clojure.org/atoms, except that enduro's is durable - its contents can be persisted as Clojure data to some durable backing store. https://github.com/alandipert/enduro This is so nice. Much easier than manually persisting/restoring an atom. Has anyone used it before?

Steiner09:05:04

how do i know where the wrong message is,too much debug message shown,and i can't find it

java.lang.ClassCastException: clojure.lang.LazySeq cannot be cast to java.lang.Number
 at  (Numbers.java:229)
    clojure.lang.Numbers.max (Numbers.java:4027)
    euler_project.11_20$solution_11.invokeStatic (form-init7724603543419221011.clj:99)
    euler_project.11_20$solution_11.invoke (form-init7724603543419221011.clj:6)
    euler_project.11_20$eval1436.invokeStatic (form-init7724603543419221011.clj:210)
    euler_project.11_20$eval1436.invoke (form-init7724603543419221011.clj:210)
    clojure.lang.Compiler.eval (Compiler.java:6927)
    clojure.lang.Compiler.eval (Compiler.java:6890)
    clojure.core$eval.invokeStatic (core.clj:3105)
    clojure.core$eval.invoke (core.clj:3101)
    clojure.main$repl$read_eval_print__7408$fn__7411.invoke (main.clj:240)
    clojure.main$repl$read_eval_print__7408.invoke (main.clj:240)
    clojure.main$repl$fn__7417.invoke (main.clj:258)
    clojure.main$repl.invokeStatic (main.clj:258)
    clojure.main$repl.doInvoke (main.clj:174)
    clojure.lang.RestFn.invoke (RestFn.java:1523)
    clojure.tools.nrepl.middleware.interruptible_eval$evaluate$fn__697.invoke (interruptible_eval.clj:87)
    clojure.lang.AFn.applyToHelper (AFn.java:152)
    clojure.lang.AFn.applyTo (AFn.java:144)
    clojure.core$apply.invokeStatic (core.clj:646)
    clojure.core$with_bindings_STAR_.invokeStatic (core.clj:1881)
    clojure.core$with_bindings_STAR_.doInvoke (core.clj:1881)
    clojure.lang.RestFn.invoke (RestFn.java:425)
    clojure.tools.nrepl.middleware.interruptible_eval$evaluate.invokeStatic (interruptible_eval.clj:85)
    clojure.tools.nrepl.middleware.interruptible_eval$evaluate.invoke (interruptible_eval.clj:55)
    clojure.tools.nrepl.middleware.interruptible_eval$interruptible_eval$fn__742$fn__745.invoke (interruptible_eval.clj:222)
    clojure.tools.nrepl.middleware.interruptible_eval$run_next$fn__737.invoke (interruptible_eval.clj:190)
    clojure.lang.AFn.run (AFn.java:22)
    java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1149)
    java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:624)
    java.lang.Thread.run (Thread.java:748)

Ben Sless09:05:06

It's a stack trace, try looking at the top of the stack

Ben Sless09:05:20

it tells you the exception:

java.lang.ClassCastException: clojure.lang.LazySeq cannot be cast to java.lang.Number

Ben Sless09:05:28

you tried comparing a sequence and a number

Steiner09:05:50

is there a macro to locate where error is?

Ben Sless09:05:30

you mean in your code?

Steiner09:05:56

no,I mean some macro like (foo my-code)

Ben Sless09:05:13

It's a bit tricky because that would require analyzing the stack. You can wrap it in try-catch which would return the exception

Steiner10:05:05

and how do i know where the error is

Ben Sless10:05:18

I think it may be in line 6 of your form you evaluated

Ben Sless10:05:26

euler_project.11_20$solution_11.invoke (form-init7724603543419221011.clj:6)

Ben Sless10:05:33

when you called solution-11

Steiner14:05:04

I want to know if there is better solution for https://projecteuler.net/problem=12, this is my solution,and it solves too slowly

(defn solution-12 []
  (let [tran-nums (fn [num]
                    (cons (filterv #(zero? (rem num %)) (range 1 num))
                          num))]
    (loop [n 1
           c (count (tran-nums n))]
      (if (= c 500)
        n
        (recur (inc n)
               (count (tran-nums (inc n))))))))

hindol16:05:49

You can quickly time it with time. How much time does it take?

hindol16:05:56

Probably you need to use prime factorization to calculate the number of factors: https://mathschallenge.net/index.php?section=faq&amp;ref=number/number_of_divisors

Steiner17:05:12

I don't know,it took minutes not until it solves out

Steiner14:05:39

what the hell is this??

=> (Integer. "5537376230")
NumberFormatException For input string: "5537376230"  java.lang.NumberFormatException.forInputString (NumberFormatException.java:65)

djanus14:05:31

Doesn't fit in a 32-bit integer. You want (Long/parseLong "5537376230")

Michael J Dorian14:05:40

2147483647 is the maximum value for a java integer

Michael15:05:46

hi all, i have this reference of vector of maps: (def l (ref [{:a 1 :c false} {:a 2 :c false} {:a 3 :c false}])) and i apply a filter on it to fetch the desired element, example: (filter #(= (:a %) 1) (deref a)) now what i want to do is to apply the filter and at the same time change the :c value in the referenced map.. so the above would then become: #<Ref@5f8b3cd8: [{:a 1, :c true} {:a 2, :c false} {:a 3, :c false}]> is there some way to do this without having to iterate the ref map again just to change the desired value?

skykanin17:05:13

(ns sudokusolver.logic
  (:refer-clojure :exclude [==])
  (:require [clojure.core.logic :refer :all]
            [clojure.core.logic.fd :as fd]))
For some reason I'm getting an ns spec error, but I can't see what's wrong with my ns deceleration

dpsutton17:05:39

:refer :all is not valid

skykanin17:05:12

ok, can I use :use instead?

dpsutton17:05:34

oh i mispoke. refer all is valid like that apparently.

dpsutton17:05:46

what's the error?

dpsutton17:05:15

does it mention something about unify?

skykanin17:05:10

it's complaining that the :require spec failed

jkxyz17:05:58

:refer :all isnā€™t supported in CLJS

dpsutton17:05:42

much preferable in general to give an alias in my opinion. [clojure.core.logic :as l]

skykanin17:05:02

yeah ok, I'll do that

skykanin17:05:59

I also see that clojure.core.logic.fd isn't supported in cljs, rip

Noah Bogart18:05:31

if I have a record Card and I use (map->Card {...}), is there an opposite function (Card->map #Card{...})?

ghadi18:05:45

records are maps already

dpsutton18:05:36

are you trying to get rid of a protocol implementation maybe?

Noah Bogart18:05:45

trying to figure out the source of a bug using differ that leads to java.lang.UnsupportedOperationException: Can't create empty: game.core.card.Card

Noah Bogart18:05:01

was wondering if it had to do with using a record instead of a map

Alex Miller (Clojure team)18:05:35

empty on records wonā€™t work (records inherently have keys)

šŸ‘ 4
ghadi18:05:23

if you post a fuller stacktrace, I suspect you'll see a call to clojure.walk/walk within it

Noah Bogart18:05:17

my apologies for the color codes, never figured out how to turn those off

ghadi18:05:05

ok, not what I expected šŸ™‚

ghadi18:05:34

but yeah it's calling empty upon a record

Noah Bogart18:05:37

right, so if I can turn the Card objects back to a map, or do some silliness like (Card->map (map->Card {...})) to get all of the :key nil, I can explore more

Noah Bogart18:05:49

thanks either way

Noah Bogart18:05:52

appreciate y'alls input

dpsutton18:05:56

it looks like records just use (into {} record) to achieve this

āœ”ļø 4
šŸ‘ 4
dpsutton18:05:37

and then the fun game of do the Card defrecords match up on both sides of the websocket šŸ™‚

dpsutton18:05:23

(and sorry for not addressing the question directly)

Noah Bogart18:05:17

no worries! always gotta be looking out for the XY problem

šŸ‘ 8
ryan echternacht18:05:01

if I have a list of kev-value pair vectors (like you get from sequencing a map), is there an easy way to get these back into a map? this is what I have (reduce (fn [m [k v]] (assoc m k v)) {} kvs) but Iā€™m curious if there is something better

ghadi18:05:04

@ryan072 (into {} pairs)

ryan echternacht18:05:32

weird @ghadiā€¦ I thought I tried that and it didnā€™t work. worked this time tho, so thanks!!

noisesmith18:05:32

the gotcha is that into only works with vectors, your reduce above would work with two elements seqs as well

ryan echternacht18:05:49

thanks @noisesmith, that makes sense

theequalizer7318:05:48

Hi! Iā€™m trying to use selmer for templating in a small web app. Iā€™m passing variables like current-user, errors, messages when I use selmer.parser/render but now I reach the point where Iā€™m trying to work with ring sessions. I can pass the session map using redirect but how can I pass the other variables I was sending with render?

seancorfield18:05:56

@orlandomr27 You could just assoc or merge the data you need into a single hash map.

seancorfield19:05:41

(selmer.parser/render template (merge (:session req) {:other :data :goes :here}) -- off the top of my head

seancorfield19:05:45

I often pass the entire req hash map to Selmer, and assoc in any extra data I need, either assoc-in into :params or as qualified top-level keys.

theequalizer7319:05:52

Thank you @seancorfield and how could I reference the keys inside req from inside the template? The same way as other variables? Like for example I want to show the username from :session {{ :session {{ username}} }} ??

seancorfield19:05:47

Use dotted notation (per the Selmer docs): {{session.username}} if you're passing the whole req

seancorfield19:05:03

{{params.foo}} to access a parameter

seancorfield19:05:06

If you're passing just the session hash map, with other data merged in -- per my code above -- then {{username}} would be the username from session, since the whole hash map is that session data.

seancorfield19:05:31

It's "just" data -- a potentially nested hash map.

theequalizer7317:05:46

I had a problem using render-file. After login the app was rendering index.html but the url was showing the login route, so I insisted in using redirect and Iā€™ve found a way to do it. session was destructured in function params

(let [next-session (assoc session :session (:user-id "1" :first-name "John"))]
          (-> (redirect "/")
              (merge next-session {:some-keys some-values)))
Then on ā€œ/ā€ route I just render-file the index.html with :session param
(parser/render-file "templates/index.html" {:session (:session req) :books books})
It is working just fine and redirecting as it should. Thanks @seancorfield for remembering me that Ā«itā€™s just data - a potentially nested mapĀ».

theequalizer7319:05:31

Nice! IĀ“m going to try that. So there is no need for response.redirect to assoc the session. Thanks!

seancorfield19:05:21

Passing the whole req is definitely the easiest way for the view templates to have access to everything they need.

Ī»raulain20:05:01

hi everyone, just out of curiosity why does (dir clojure.string) in the lein repl return the names of the functions in that namespace but in the calva repl return an error Unable to resolve symbol: dir in this context

dpsutton20:05:12

dir is a macro defined in clojure.repl . So if the macro is visible from your current namespace it will work. But in an arbitrary namespace it won't be there

dpsutton20:05:31

(apply require clojure.main/repl-requires) is what many repls run in the user namespace so these helpful bindings are present

šŸ‘ 4
šŸ’Æ 4
dpsutton20:05:51

and the source of clojure.main/repl-requires:

(def ^{:doc "A sequence of lib specs that are applied to `require`
by default when a new command-line REPL is started."} repl-requires
  '[[clojure.repl :refer (source apropos dir pst doc find-doc)]
    [clojure.java.javadoc :refer (javadoc)]
    [clojure.pprint :refer (pp pprint)]])

dpsutton20:05:17

(i actually didn't know pprint was required). so great question!

šŸ˜ 4
šŸ‘ 4
Ī»raulain20:05:46

that's true @dpsutton I tried (clojure.repl/dir clojure.string) in the calva repl and it worked

noisesmith21:05:24

when I discovered clojure.main/repl-requires it also reminded me of the very useful javadoc function, which I use a lot more now - you can pass it an arbitrary object and it will usually find the web page with that object's api

šŸ‘ 4
noisesmith21:05:44

and if not the query bar is partially filled in for my own google search :D

dpsutton21:05:24

there's a ticket for >java11 unfortunately

noisesmith21:05:42

oh, I haven't tried java12 so haven't run into that

dpsutton21:05:11

for 13 it falls back to 8. it also doesn't handle outside of java.lang maybe? bit hazy on details now

dpsutton21:05:32

ah, java.base i think

seancorfield21:05:29

Yeah, I use the internals of javadoc as part of my Atom/Chlorine/REBL integration so I can view HTML pages inside REBL and navigate between them. I also have an equivalent for ClojureDocs inside REBL (but that's not as sophisticated).

noisesmith22:05:11

wow, that's cool

dpsutton22:05:43

yeah that's really cool

Ramon Rios23:05:25

(map #(- 15 %) [20 10 35])

(map (partial - 15) [20 10 35])
they do the same thing. But witch one is the best option for use?

noisesmith23:05:15

it's a question of style but I tend to reserve partial for more complex higher order / point free situations, and use #() in a simple case like that one

noisesmith23:05:33

and I'd switch from #() to fn (ideally with the optional name parameter included) for cases where there's any nested calls

Ramon Rios23:05:22

I understand what partial is and it's results. But i still not understand in a practical way how can i solve something with it

Ramon Rios23:05:57

partial will return me a function with a parameter already filled and then i have to call this returned function with something that is missed.

Ramon Rios23:05:12

Anyway, i'll keep going in my studies

noisesmith23:05:14

for example (def rotate-table (partial apply mapv vector)) - in this case I'm already working point free, and it's natural to add partial in, it "speaks the same language" as things like apply, comp, juxt etc. which are used in order to stack function calls instead of naming temprorary variables

noisesmith23:05:11

(defn rotate-table [t] (apply mapv vector t)) and (def rotate-table #(apply mapv %)) would do the same thing, but stylistically partial fits better

noisesmith23:05:47

there's also cases where partial avoids a call to apply - eg. (partial list :prefix) as apposed to #(apply list :prefix %&)

noisesmith23:05:18

since partial makes no assumptions about argument count of the thing it returns

theequalizer7317:05:46

I had a problem using render-file. After login the app was rendering index.html but the url was showing the login route, so I insisted in using redirect and Iā€™ve found a way to do it. session was destructured in function params

(let [next-session (assoc session :session (:user-id "1" :first-name "John"))]
          (-> (redirect "/")
              (merge next-session {:some-keys some-values)))
Then on ā€œ/ā€ route I just render-file the index.html with :session param
(parser/render-file "templates/index.html" {:session (:session req) :books books})
It is working just fine and redirecting as it should. Thanks @seancorfield for remembering me that Ā«itā€™s just data - a potentially nested mapĀ».