Clojure does not have !=? - clojure

Does not exist?

Does exist:
Clojure 1.2.0
user=> (not= 1 2)
true
user=> (not= 1 1)
false

user=> (doc not=)
-------------------------
clojure.core/not=
([x] [x y] [x y & more])
Same as (not (= obj1 obj2))
nil
Amusingly, you could define != to be the same as not= if you really wanted:
user=> (def != not=)
#'user/!=
user=> (!= 2 2)
false
user=> (!= 2 3)
true

In a lot of clojure code the ! char means that a function changes the state of something in a way you should watch out for. the clojure transients make heavy use of these
compare-and-set!
alter-meta!
conj!
persistent!
check out http://clojure.github.com/clojure/ and search for the ! character. these functions usually come with caveats like "must be free of side effects"

According to my google search "not=" is the equivalent but I have zero personal familiarity with Clojure.

Is there some reason not= doesn't suit your purposes?

Related

What is :some-parameter in Clojure?

I'm learning Clojure and I have seen pieces of code with :some-value. What's that ? I saw some code like this
(defn relay [x i]
(when (:next x)
(send (:next x) relay i))
(when (and (zero? i) (:report-queue x))
(.put (:report-queue x) i))
x)
if I print the when documentation, I don't find :next there
(doc when)
-------------------------
clojure.core/when
([test & body])
Macro
Evaluates test. If logical true, evaluates body in an implicit do.
nil
Where is :next definition ?
Thanks!
Those are keywords. Googling what they are can be surprisingly difficult if you don't already know what they are.
They evaluate to themselves:
user=> :foo ; evaluates to :foo
They are unique, potentially namespace-qualified identifiers. Which is why they are frequently used as keys in maps:
(def stuff {:a 1
:b 2})
They know how to look themselves up (i.e. you can call them as functions):
(:a stuff) ; 1
...which is the use-case in your example code. They're quite nice.

Idiomatic `and` & `or` functions (not macros) in Clojure

Strange as it may sound, I am looking for function versions of the and and or macros in Clojure.
Why? For one I am curious.
Second, I want to use or in precondition and postcondition checks. This does not work:
(defn victor
[x]
{:post (or (nil? %) (vector %))}
;; ...
)
I want the postcondition to check to see if victor returns a vector or nil, but it fails:
#<CompilerException java.lang.RuntimeException: Can't take value of a macro: #'clojure.core/or, compiling:(test/test.clj:10:1)>
I don't think bit-and and bit-or are quite what I'm looking for.
Update: This syntax works without an error:
(defn victor
[x]
{:post [(or (nil? %) (vector %))]}
;; ...
)
I'm still curious if functions exist, though.
I think the standard method is simply to wrap and and or in functions, e.g. (fn [x y] (or x y)). In some contexts, another function will work. For example, a note in the clojure docs for and suggests using (every? identity [true false]). some, not-every?, and not-any? can be used in a similar way.
In general, and and or functions would be undesirable because they cannot use short-circuiting. Consider the following code:
(and false some-expensive-fn)
(or true some-expensive-fn)
With and and or as macros the above code won't execute some-expensive-fn, because it is unnecessary to determine the overall truth value of the expression. In function expressions the arguments are evaluated before being passed to the function, but in macros they are not.
#Triangle Man is right. Short-circuiting won't work, but nevertheless you can define your own function versions:
user=> (defn && [x y] (and x y))
#'user/&&
user=> (&& true false)
false
user=> (&& true true)
true
user=> (defn || [x y] (or x y))
#'user/||
user=> (|| true false)
true
user=> (|| true true)
true
user=> (|| false false)
false
user=>

Consolidated cond arguments in Clojure (CL style)

In Clojure I do this
(println (cond false "don't care" "otherwise" "otherwise"))
In Common LISP this would be
(print (cond (nil "don't care") ("otherwise") ))
Is there a way to get this kind of simplified cond in Clojure?
Version which includes a fix for that Alex Taggart noticed below. Passes all the test cases shown in the test. It allows for arbitrary clauses passed to my-cond to be length 1 instead of 2 which results in the length 1 clause being both the test for truthiness and the result if it is true. Based off my limited experience with CL I actually think this behavior is different from what cond does but seems to be in line with how I've interpreted what you're asking for. Kotarak's answer seems to line up with the CL one as using the last statement in the CL cond seems to match up with using the :else clause in the Clojure version.
Regardless here is a solution where it should allow any clause to be a length of one and use that for both the truth test and result.
(defmacro my-cond
[& others]
(if others
(let [more# (next others)
extra-clauses# (if more# `(my-cond ~#more#))
clause# (first others)]
(if (= 2 (count clause#))
`(if ~(first clause#) ~(second clause#) ~extra-clauses#)
`(if ~(first clause#) ~(first clause#) ~extra-clauses#)))))
(deftest my-cond-works
(is (= 3 (my-cond (false 1) (false 2) (3))))
(is (= "otherwise" (my-cond (false "don't care") ("otherwise"))))
(is (= nil (my-cond (:one nil) ("otherwise"))))
(is (= "care" (my-cond (1 "care") ("otherwise"))))
(is (= "otherwise" (my-cond (false "care") ("otherwise") (true "true"))))
(is (= "silly" (my-cond (nil "no") (nil) ("yes" "silly")))))
I'd really advise translating the CL over to the Clojure form of cond. I would place the mental overhead of allowing the CL syntax along with the Clojure syntax in the same project as not worth saving time in translating it now. Looking at the code in the future after becoming used to how Clojure's cond and trying to remember why the other syntax is there seems not worth the time saved by not translating.
Below version fails as Alex Taggart says below. Keeping it here so his comment makes sense.
The below version does:
(defmacro my-cond [[if1 then1] & others]
(when (or if1 then1 others)
(let [extra-clauses# (if others `(my-cond ~#others))]
(if then1
`(if ~if1 ~then1 ~extra-clauses#)
`(if ~if1 ~if1 ~extra-clauses#)))))
user> (my-cond (false "first") (nil nil) ("otherwise"))
"otherwise"
I believe the clojure version was intended to have fewer parens. You can certainly write your own cond-ish macro to do what you want.
Here is a simple implementation (i.e. does not implement the full CL version)...
(defmacro my-cond [[if1 then1] & others]
(if others
`(if ~if1 ~then1 (my-cond ~#others))
`(if ~if1 ~then1)))
And you can then...
(my-cond (false 1) (false 2) (3 3)) ; results in 3
An important feature of the CL cond is that if any of the operands of cond is a singleton, then the element within the singelton is evaluated, and if that value is non-nil, it is returned without evaluating it a second time.
(cond
(a 100)
((f 1 2 3))
(b 200))
This form evaluates to 100 if a is true, else to the value of (f 1 2 3) if that is non-nil, else to 200 if b is non-nil, else to nil.
I believe what you need is the following.
(defmacro my-cond [[if1 & then1] & others]
(when (or if1 then1 others)
(let [extra-clauses# (if others `(cl-cond ~#others))]
(if then1
`(if ~if1 (do ~#then1) ~extra-clauses#)
`(or ~if1 ~extra-clauses#)))))

How to evaluate a sequence of impure functions in Clojure?

How can I evaluate a list of (impure) functions in Clojure? For instance:
[#(println "1") #(println "2") #(println "3")]
The expected output is:
1
2
3
Is there a way to achieve this without using macros? Something like (map evaluate fns-seq), maybe?
(I need this for drawing some graphics using the Clojure.processing API.)
user> (let [fs [#(println "1") #(println "2") #(println "3")]]
(doseq [f fs] (f)))
1
2
3
nil
This will eagerly consume the whole seq, calling all functions for side effects and returning whatever the last one returns:
(reduce #(%2) nil [#(println :foo) #(println :bar)])
; => prints :foo, then :bar, then returns nil
If you want to hold onto the return values, you can use reductions instead:
(reductions #(%2) nil [#(println :foo) #(println :bar)])
; => prints :foo, then :bar, then returns (nil nil)
reductions is found in clojure.contrib.seq-utils in Clojure 1.1 and in clojure.core in current snapshots of 1.2.
Update: Note that reductions returns a lazy seq, so it's no improvement over map (NB. in map you'd want to use #(%) rather than #(%2)). I mentioned it here mostly for completeness. In fact, I posted the whole answer for completeness, because normally I'd go with the doseq approach (see Brian's answer).
(apply pcalls [#(println "1") #(println "2") #(println "3")]) does just that. Just be wary of pcalls' parallelism (therefore lack of sequentiality) and lazyness.
An old question, I know, but there's another option.
You could simply invoke the functions:
(defn generate-fns []
[#(println "1") #(println "2") #(println "3")])
(dorun (pmap (memfn invoke) (generate-fns)))
This allows you to decide in a different context how you would like to execute the functions (say, pmap, or claypoole's upmap for example)

Function composition in Clojure?

Can Clojure implement (g ∘ f) constructions like Haskell's g . f? I'm currently using workarounds like (fn [n] (not (zero? n))), which isn't nearly as nice :)
There is a function to do this in clojure.core called comp. E.g.
((comp not zero?) 5)
; => true
You might also want to consider using -> / ->>, e.g.
(-> 5 zero? not)
; => true
You can use Clojure's reader-macro shortcut for anonymous functions to rewrite your version in fewer keystrokes.
user=> (#(not (zero? %)) 1)
true
For the specific case of composing not and another function, you can use complement.
user=> ((complement zero?) 1)
true
Using not in combination with when and if is common enough that if-not and when-not are core functions.
user=> (if-not (zero? 1) :nonzero :zero)
:nonzero
Another way is (reduce #(%2 %1) n [zero? not]) but I like (comp not zero?), already mentioned by Michal, better.