Clojure function throws casting exception on println? How can one keep function & correct error? - clojure

Outside of the function, the code works as expected, but in the following code it returns exception on a test site [Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to clojure.lang.IFn]
How can I keep the function structure & get the results to print?
(defn sumTerm [hi lo]
(if (< hi lo)
(0)
(let [
terms (quot hi lo)
tb (+ terms 1)
]
(quot (* lo terms tb) 2)
)
))
let [
ln 27
a (sumTerm ln 4)
b (sumTerm ln 7)
abc (- (+ a b) (sumTerm ln 28))
]
(println " abc= "(str abc))

It cannot work as expected unless you never hit the (< hi lo)'s "then" branch, because you're trying to call 0 as a function by wrapping it in parentheses.
Try replacing (0) with just 0.

Related

Factorial iterative illegal argument - clojure

(defn fac [n]
(def result 1)
(loop [i n c 1]
(if (<= c 5)
result
(recur (* c i) (inc c))
)
)
(println result)
)
(fac 5)
Error:Exception in thread "main" java.lang.IllegalArgumentException: loop requires a vector for its binding.
I am trying to write a function that evaluates a numbers factorial. Where is my mistake? It gives me 1 as answer
At first sight:
Don't use a def inside a defn.
The REPL will print the result of evaluating a function. Use it.
This gets us to
(defn fac [n]
(loop [i n c 1]
(if (<= c 5)
result
(recur (* c i) (inc c)))))
... which doesn't compile, because result is floating.
There are a few corrections required:
Return i, not result.
Start i at 1, not n.
Turn the test around: > instead of <=.
We end up with
(defn fac [n]
(loop [i 1, c 1]
(if (> c n)
i
(recur (* c i) (inc c)))))
... which works:
(fac 5)
=> 120
Edited to correct one-off error and improve explanation.

Calling a macro on a macro

I'm trying to write a Clojure macro that creates a prefix notation list for evaluation from a simple infix notation list, say (2 * 3 + 4 * 2) to an evaluated(+ (* 2 3) (*4 2)) (resulting in 14 being returned).
I have written the following code:
(defmacro infix [op inlist]
(let [[i1 i2 & i3] inlist
last-group? (nil? (second i3))]
(if last-group?
`(if (= ~op ~i2)
(~i2 ~i1 ~(first i3)) ; return unevaluated prefix list
(~i1 ~i2 ~(first i3))) ; return unevaluated infix list
`(if (= ~op ~i2)
; recur with prefix list in i1 position
(infix ~op ~(conj (rest i3) (list i2 i1 (first i3)) ))
; return as list: i1 and i2, recur i3 (probably wrong)
(~i1 ~i2 (infix ~op ~i3))
))))
With the intention of enforcing operator precedence by calling the macro recursively with different op (operator function) parameters:
(infix + (infix * (2 * 3 + 4 * 2)))
Above, I'm just using it with two * and +, but ultimately I'd want to call the macro for all (or at least for the sake of this exercise, / * + -) operators.
When I execute the above nested macro call, I get the following error:
CompilerException java.lang.RuntimeException: Can't take value of a macro: #'cbat.ch7.ex2/infix, compiling:(/tmp/form-init4661580047453041691.clj:1:1)
Calling the macro for a single operator and a list of the same operator (i.e. (infix * (2 * 3 * 4))) works as expected. If I call the macro with a single (i1 i2 i3) list, if op differs from i2, it tries to (understandably) return the unevaluated infix list with the error:
ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn cbat.ch7.ex2/eval3003 (form-init4661580047453041691.clj:1)
I was hoping calling the macro recursively would mean that I could process the unevaluated infix list before the entire line was evaluated, but this doesn't seem to work.
I'm pretty sure the else branch of the latter, inner if (i.e. (~i1 ~i2 (infix ~op ~i3))) is incorrect and I may just need the inner infix call, but I'm more concerned with getting the nested macro calls for the different operators working prior to evaluation.
I know that this isn't the usual way of converting infix to prefix notation, and have since found out about Dijkstra's shunting-yard algorithm, but please could someone kindly enlighten me as to:
whether such nested macro calls are possible?
whether my logic is reasonable, and not too far from a solution? If so...
... what changes I need to make to get things running?
I'm really focused on learning Clojure, so any thorough explanation (where possible) will be most welcome.
You can nest macro calls as this code demonstrates:
(defmacro mac [tag & forms]
`(do
(println "mac - enter" ~tag)
~#forms
(println "mac - exit " ~tag)))
(mac :a
(doseq [i (range 3)]
(mac :b (println i))))
mac - enter :a
mac - enter :b
0
mac - exit :b
mac - enter :b
1
mac - exit :b
mac - enter :b
2
mac - exit :b
mac - exit :a
You can also make recursive macro calls as this shows:
(defmacro macr [n]
(if (zero? n)
1
`(* ~n (macr ~(dec n)))))
(macr 5) => 120
Without delving too deep into your particular implementation, I would suggest 2 points:
At least to start, keep your forms as simple as possible. This means only forms like (2 + 3). And especially don't force the macro to figure out operator precedence in the early versions (or ever!).
Macros are almost never necessary, and it is unfortunate IMHO that they are somewhat "over-hyped" when learning Clojure & other lisps. I would suggest you don't even think about them for the first year or two, as they are more brittle than functions and less powerful in important ways (you can't pass a macro into a function, for example).
Update
Whenever you want to write something complicated (a macro definitely qualifies!), start small and
build it up one step at a time. Using the lein-test-refresh plugin and the Tupelo library definitely help
here.
First, make the simplest possible macro and observe its behavior:
(ns tst.clj.core
(:use clj.core clojure.test tupelo.test)
(:require [tupelo.core :as t] ))
(t/refer-tupelo)
(defn infix-fn [[a op b]]
(spyx a)
(spyx op)
(spyx b)
)
(defmacro infix [form]
(infix-fn form))
(infix (2 + 3))
a => 2
op => +
b => 3
For many macros, it is helpfully to send the marcro args to a helper function like infix-fn. The
spyx helps us by printing the symbol and its value. At this point, we can simply re-order the
args into prefix notation and away we go:
(defn infix-fn [[a op b]] (list op a b))
(defmacro infix [form] (infix-fn form))
(deftest master
(is= 5 (infix (2 + 3)))
(is= 6 (infix (2 * 3))))
What if we have a recursive tree structure? Check if we need to recurse in infix-fn:
(declare infix-fn)
(defn simplify [arg]
(if (list? arg)
(infix-fn arg)
arg))
(defn infix-fn [[a op b]]
(list op (simplify a) (simplify b)))
(is= 7 (infix ((2 * 2) + 3)))
(is= 9 (infix ((1 + 2) * 3)))
(is= 35 (infix ((2 + 3) * (3 + 4))))
(is= 26 (infix ((2 * 3) + (4 * 5))))
I would not want to add in the complication of operator precedence. If absolutely necessary, I
would not code it up myself but would use the excellent Instaparse library for that purpose.
expansion of your call would give you a clue:
(if (= + *)
(* infix (2 * 3 + 4 * 2))
(infix * (2 * 3 + 4 * 2)))
You've got the wrong presumption that the argument of macro would be expanded before the macro itself, i guess. But in fact in this one: (~i2 ~i1 ~(first i3)) i1 is still infix symbol. As far as i can see, the solution is to add some new condition branch, treating infix form some special way.

How do I define a safe sqrt function in clojure?

I am using fungp (a genetic programming tool) to model a complex function and having trouble with sqrt.
Basically, I have to pass a vector of functions and their arity into fungp so that it can compose expressions from them. The expressions will then be evaluated and the best one will be returned. This vector of functions looks like:
(def functions
'[[+ 2]
[- 2]
[* 2]
[fungp.util/abs 1]
[fungp.util/sdiv 2]
[fungp.util/sin 1]
[fungp.util/sqrt 1]
[inc 1]
[dec 1]])
That setup gives me a hundred lines of errors like:
#<ClassCastException java.lang.ClassCastException: java.lang.Double cannot be cast to clojure.lang.IFn>
Which I believe is due to the definition of fungp.util/sqrt:
(defn sqrt [x] (if (x > 0) (Math/sqrt x) 0))
I think the 0 is causing the failure to evaluate, but I'm not sure. I've tried defining my own version of the safe square root, but couldn't get the syntax correct.
So, this is where I'm stuck. I need a version of square root that is safe (returns 0 for negative inputs) and evaluates properly in the fungp expression.
EDIT: For completeness, this is one of the (many) variations I've tried for writing my own square root wrapper:
(defn sqrt-fn [x] `(if (~x > 0) (Math/sqrt ~x) 0))
And the output (the middle bit is the expression that was generated from the functions):
#<ClassCastException java.lang.ClassCastException: clojure.lang.Cons cannot be cast to java.lang.Number>
(let [] (- (dec (- (- (fungp.util/sin (tutorial.tut1/sqrt-fn 8.0)) (fungp.util/sdiv (* x 2.0) (dec 9.0))) (fungp.util/sdiv (tutorial.tut1/sqrt-fn (* x x)) (- (- x 4.0) (+ x x))))) (fungp.util/sdiv (tutorial.tut1/sqrt-fn (fungp.util/sin (
+ (dec x) (inc x)))) (fungp.util/sdiv (* (inc (inc 1.0)) (* (+ x 9.0) (fungp.util/sin 9.0))) (tutorial.tut1/sqrt-fn (- (tutorial.tut1/sqrt-fn x) (fungp.util/abs 3.0)))))))
NullPointerException clojure.lang.Numbers.ops (Numbers.java:942)
I am not writing the expressions, so if there are extra parentheses or missing parentheses, they are coming from the way that I've defined sqrt.
There are a couple of things wrong with this:
(defn sqrt-fn [x] `(if (~x > 0) (Math/sqrt ~x) 0))
First, as hinted at in the comments, (x > 0) is trying to call x (presumably a number) as a function. > is the function, so it must come first, as in (> x 0).
Also, you probably don't want they syntax quote here - that prevents evaluation of the contents, so your function is returning a quoted list of symbols.

How to call one defn function in another defn and how to debugging in Clojure

I am having a problem running my program in Clojure. I just start learning Clojure a couple of weeks ago. So I don't know the quick and easy way to debug a Clojure program. My func2 raises an exception at (adj(a b)) as followed:
ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn
user/func2.
I don't know what is wrong with it. Can someone point out the problem with my coding?
And in func3, I call func2 recursively, but it throws:
ArityException Wrong number of args (0) passed to: PersistentVector
clojure.lan g.AFn.throwArity (AFn.java:437)
What is wrong with func3? Thank you.
(defn adj [value1 value2]
(def result (+ (/ value1 2) (/ value2 2)))
(if (= (mod result 2) 1)
(+ result 1)
result
)
)
(defn func2 [list]
(let [[a b c d] list]
(inc d)
([(adj c a) (adj a b) (adj b c) d]))
)
(defn func3 [list]
(loop [v list r []]
(if(= (v 0) (v 1) (v 2))
(conj list r)
(func3(func2(list)))
))
)
What's the intended result of these functions? We probably need to see some sample inputs and expected results to really be able to help you.
Here's my attempt at cleaning them up. I've noted the changes I made as comments. func3 has the most serious problem in that it's an infinite recursion - there's no end condition. What should cause it to stop working and return a result?
(defn adj [value1 value2]
;; don't use def within functions, use let
(let [result (+ (/ value1 2) (/ value2 2))]
(if (= (mod result 2) 1)
(+ result 1)
result)))
(defn func2 [list]
(let [[a b c d] list]
;; The extra parens around this vector were causing it
;; to be called as a function, which I don't think is
;; what you intended:
[(adj c a) (adj a b) (adj b c) d]))
;; This needs an end condition - it's an infinite recursion
(defn func3 [list]
(loop [v list r []]
(if (= (v 0) (v 1) (v 2))
(conj list r)
;; Removed extra parens around list
(func3 (func2 list)))))
The reason I say not to use def within functions is that it always creates a global function. For local bindings you want let.
Regarding the extra parens, the difference between [1 2 3] and ([1 2 3]) is that the former returns a vector containing the numbers 1, 2, and 3, whereas the latter tries to call that vector as a function. You had excess parens around the literal vector in func2 and around list in func3, which was causing exceptions.
As a style note, the name list isn't a good choice. For one thing, it's shadowing clojure.core/list, and for another you're probably using vectors rather than lists anyway. It would be more idiomatic to use coll (for collection) or s (for sequence) as the name.
This would suggest at least one other change. In func3 you use a vector-only feature (using the vector as a function to perform lookup by index), so to be more general (accept other data structures) you can convert to a vector with vec:
(defn func3 [coll]
(loop [v (vec coll) r []]
(if (= (v 0) (v 1) (v 2))
(conj v r)
(func3 (func2 v)))))
Oh, there is no need to debug that. I suggest you have a look at LightTable.
The first two functions are easily fixed:
(defn adj [value1 value2]
;(def result (+ (/ value1 2) (/ value2 2))) def creates a global binding in current namespace !!!
(let [result (+ (/ value1 2) (/ value2 2))]
(if
(= (mod result 2) 1)
(inc result)
result)))
(defn func2 [xx]
(let [[a b c d] xx]
[ (adj c a) (adj a b) (adj b c) (inc d)]
))
The third function is not clear to me. I don't read your intent. What I understand is: "Keep applying func2 to itself until the first three elements of its result are equal." But I'm afraid this condition is never met, so I replaced it with a true in order to see just one result without blowing the stack.
(defn func3 [xx]
(loop [ v (func2 xx) ]
(if
;(= (v 0) (v 1) (v 2))
true
v
(recur (func2 v))
)))
Useful link: http://clojure.org/cheatsheet
Cheers -

NullPointerException after simple clojure program

I am working on learning clojure, and have run into a NullPointerException that seems to have nothing to do with my code. The program runs to completion before producing the error. The code:
; solves the collatz conjecture
; return one step in the sequence
(defn collatz-step [n]
(if (= (rem n 2) 0)
(/ n 2)
(+ 1 (* 3 n))))
; recurse over all numbers
(defn collatz [n]
(if (= n 1)
(println "All done!")
((println (format "N = %d" n))
(collatz (collatz-step n)))))
; get input and run it
(println "Enter a positive number:")
(collatz (read-string (read-line)))
Is there something I'm missing?
when this line runs:
((println (format "N = %d" n))
(collatz (collatz-step n)))
the println and colatz will finish leving the form like this:
(return-value-of-println return-value-of-collatz)
println returns nil yielding:
(nil return-value-of-collatz)
which is a function call to the function nil resulting in an NPE
take out the extra ()
Clojure does not have tail call elimination, so changing your recursive call to collatz to recur will keep it from blowing the stack on large values of n