Is there a function that takes a list of argument lists and applies each list to a given function? - function

I.e., something like:
(defn dowith [f & arglists]
(doseq [args arglists] (apply f args)))
Is there a built-in function like that in Clojure?

I write things like that moderately often; its just so short that it's not really worth wrapping:
(map #(apply myfun %) list-of-arglists)
I use map most often so i get the results and keep it lazy. of course if you don't want it lazy and don't want the results then doseq is fine also.

No, there is no built-in function that does that.

Related

CLJS: Setting a JS property to the result of calling a method on it

I'm looking to modify some existing text in a web app, which I'm accessing with expressions like this:
(.-innerHTML (.getElementById js/document "myElementId"))
What I specifically want to do is mutate that text via a search/replace:
(set! (^that whole thing) (.replace (^that whole thing) "old" "new"))
And I'd ideally like to do that without having to repeat the property-access expression. Is there any existing shortcut for this? I'm envisioning something like Raku's object .= method(args) shorthand for object = object.method(args); maybe a good clj name/pattern would be (.set! (access-expression) method & args). I can always write a macro, but was wondering if I'd overlooked something already there.
I was curious too and looked in the CLJS CheatSheet and they link to the CLJS Oops library which provides similarly looking functions.
It seems to be that the most robust solution would be to just rely on the Google Closure Library (which is always at hand) and use a combination of goog.object/get and goog.object/set (no need for a macro), something like:
(require 'goog.object)
(defn update-obj! [obj field f & args]
(let [old-val (goog.object/get obj field)
new-val (apply f old-val args)]
(goog.object/set obj field new-val)))
;; Example:
(update-obj! (.getElementById js/document "my-div") "innerHTML" (partial str "it works: "))
This should work in both development and optimized output.

Can I return early (mid-function) in ClojureScript?

I have a function that is iterating over a moderately sized list of strings and is looking through some JSON returned from a server for the existence of a value in the data. The code will be run many times, so I want it to be fast. Is there any way I can return as soon as I find the value I'm looking for?
(defn find-type [js-data-set]
(doseq [type all-type-strs]
(when (aget js-data-set type)
(return true)))) ; is there a way to do this?
The built-in some function will find the first value matching a predicate, which fits this case rather nicely. More generally, you can use loop / recur, though that's rarely the most idiomatic option.
(defn find-type [js-data-set]
(some #(goog.object/get js-data-set %) all-type-strs))

Anonymous function shorthand

There's something I don't understand about anonymous functions using the short notation #(..)
The following works:
REPL> ((fn [s] s) "Eh")
"Eh"
But this doesn't:
REPL> (#(%) "Eh")
This works:
REPL> (#(str %) "Eh")
"Eh"
What I don't understand is why (#(%) "Eh") doesn't work and at the same time I don't need to use str in ((fn [s] s) "Eh")
They're both anonymous functions and they both take, here, one parameter. Why does the shorthand notation need a function while the other notation doesn't?
#(...)
is shorthand for
(fn [arg1 arg2 ...] (...))
(where the number of argN depends on how many %N you have in the body). So when you write:
#(%)
it's translated to:
(fn [arg1] (arg1))
Notice that this is different from your first anonymous function, which is like:
(fn [arg1] arg1)
Your version returns arg1 as a value, the version that comes from expanding the shorthand tries to call it as a function. You get an error because a string is not a valid function.
Since the shorthand supplies a set of parentheses around the body, it can only be used to execute a single function call or special form.
As the other answers have already very nicely pointed out, the #(%) you posted actually expands to something like (fn [arg1] (arg1)), which is not at all the same as (fn [arg1] arg1).
#John Flatness pointed out that you can just use identity, but if you're looking for a way to write identity using the #(...) dispatch macro, you can do it like this:
#(-> %)
By combining the #(...) dispatch macro with the -> threading macro it gets expanded to something like (fn [arg1] (-> arg1)), which expands again to (fn [arg1] arg1), which is just want you wanted. I also find the -> and #(...) macro combo helpful for writing simple functions that return vectors, e.g.:
#(-> [%2 %1])
When you use #(...), you can imagine you're instead writing (fn [args] (...)), including the parentheses you started right after the pound.
So, your non-working example converts to:
((fn [s] (s)) "Eh")
which obviously doesn't work because the you're trying to call the string "Eh". Your example with str works because now your function is (str s) instead of (s). (identity s) would be the closer analogue to your first example, since it won't coerce to str.
It makes sense if you think about it, since other than this totally minimal example, every anonymous function is going to call something, so it'd be a little foolish to require another nested set of parens to actually make a call.
If you're in doubt what your anonymous function gets converted to, you can use the macroexpand procedure to get the representation. Remember to quote your expression before passing it to macroexpand. In this case we could do:
(macroexpand '#(%))
# => (fn* [p1__281#] (p1__281#))
This might print different names for p1__281# which are representations of the variables %.
You can also macroexpand the full invocation.
(macroexpand '(#(%) "Eh"))
# => ((fn* [p1__331#] (p1__331#)) "Eh")
Converted to more human readable by replacing the cryptic variable names by short names. We get what the accepted answers have reported.
# => ((fn* [s] (s)) "Eh")
Resources:
https://clojure.org/guides/weird_characters#_n_anonymous_function_arguments
https://clojuredocs.org/clojure.core/macroexpand

Is the Macro argument a function?

I am trying to determine whether a given argument within a macro is a function, something like
(defmacro call-special? [a b]
(if (ifn? a)
`(~a ~b)
`(-> ~b ~a)))
So that the following two calls would both generate "Hello World"
(call-special #(println % " World") "Hello")
(call-special (println " World") "Hello")
However, I can't figure out how to convert "a" into something that ifn? can understand. Any help is appreciated.
You might want to ask yourself why you want to define call-special? in this way. It doesn't seem particularly useful and doesn't even save you any typing - do you really need a macro to do this?
Having said that, if you are determined to make it work then one option would be to look inside a and see if it is a function definition:
(defmacro call-special? [a b]
(if (#{'fn 'fn*} (first a))
`(~a ~b)
`(-> ~b ~a)))
This works because #() function literals are expanded into a form as follows:
(macroexpand `#(println % " World"))
=> (fn* [p1__2609__2610__auto__]
(clojure.core/println p1__2609__2610__auto__ " World"))
I still think this solution is rather ugly and prone to failure once you start doing more complicated things (e.g. using nested macros to generate your functions)
First, a couple of points:
Macros are simply functions that receive as input [literals, symbols, or collections of literals and symbols], and output [literals, symbols, or collections of literals and symbols]. Arguments are never functions, so you could never directly check the function the symbol maps to.
(call-special #(println % " World") "Hello") contains reader macro code. Since reader macros are executed before regular macros, you should expand this before doing any more analysis. Do this by applying (read-string "(call-special #(println % \" World\") \"Hello\")") which becomes (call-special (fn* [p1__417#] (println p1__417# "world")) "Hello").
While generally speaking, it's not obvious when you would want to use something when you should probably use alternative methods, here's how I would approach it.
You'll need to call macroexpand-all on a. If the code eventually becomes a (fn*) form, then it is guaranteed to be a function. Then you can safely emit (~a ~b). If it macroexpands to eventually be a symbol, you can also emit (~a ~b). If the symbol wasn't a function, then an error would throw at runtime. Lastly, if it macroexpands into a list (a function call or special form call), like (println ...), then you can emit code that uses the thread macro ->.
You can also cover the cases such as when the form macroexpands into a data structure, but you haven't specified the desired behavior.
a in your macro is just a clojure list data structure (it is not a function yet). So basically you need to check whether the data structure a will result is a function or not when it is evaluated, which can be done like show below:
(defmacro call-special? [a b]
(if (or (= (first a) 'fn) (= (first a) 'fn*))
`(~a ~b)
`(-> ~b ~a)))
By checking whether the first element of the a is symbol fn* or fn
which is used to create functions.
This macro will only work for 2 cases: either you pass it a anonymous function or an expression.

Clojure simple sort function error

I'm new in clojure, i try create functions thats will be sort collections and store it in object.
My code:
(defn uniq [ilist]
([] [])
(def sorted (sort ilist)))
I try to run it:
(uniq '(1,2,3,6,1,2,3))
but get error:
#<CompilerException java.lang.IllegalArgumentException: Key must be integer (NO_SOURCE_FILE:0)>
What's wrong?
Thank you.
As with your other question, you're trying to use pattern-matching where it just doesn't apply. Your function would work fine1 if you deleted the ([] []) entirely.
1 You also shouldn't use def here; as the other respondents have noted, you want to use let for establishing local bindings. However, here you don't need any bindings at all: just return the result of the sort call. In fact, the def will cause you to return a Var instead of the actual sorted list.
Since there's no need at all to use either 'let' or 'def', I have to agree with amalloy about Bart J's answer. Sure it warrants the upvotes because it's useful info, but it's not the right answer.
Actually, defining the function is kind of useless, since (sort ilist) would do the trick. The result of the function is the 'object' you want. That is, unless you want to use the result of the sort multiple times at different places in the function body. In that case, bind the result of sort to a function local variable.
If you only need the sort once, don't bother binding it at all, but just nest it inside other functions. For instance if you want to use it inside a unique function (which I guess is what you're wanting to do):
(defn uniq
"Get only unique values from a list"
[ilist]
; remove nils from list
(filter #(not(nil? %))
; the list of intermediate results from (reduce comppair sortedlist)
; (includes nils)
(reductions
; function to extract first and second from a list and compare
(fn comppair
[first second & rest]
(if (not= first second) second))
; the original sort list function
(sort ilist))))
(uniq '(1,2,3,6,1,2,3))
(1 2 3 6)
Then again, you could also just use the built-in distinct function, and take a look at it's source:
(distinct '(1,2,3,6,1,2,3))
(1 2 3 6)
(source distinct)
(defn distinct
"Returns a lazy sequence of the elements of coll with duplicates removed"
{:added "1.0"}
[coll]
(let [step (fn step [xs seen]
(lazy-seq
((fn [[f :as xs] seen]
(when-let [s (seq xs)]
(if (contains? seen f)
(recur (rest s) seen)
(cons f (step (rest s) (conj seen f))))))
xs seen)))]
(step coll #{})))
To store the sorted collection into a variable do this:
(let [sorted (sort your-collection)])
To understand the difference between a let and a def, this should help:
You can only use the lexical bindings made with let within the scope of let (the opening and closing parens). Let just creates a set of lexical bindings. def and let do pretty much the same thing. I use def for making a global binding and lets for binding something I want only in the scope of the let as it keeps things clean. They both have their uses.