Clojure Collatz Conjecture NullPointerException - recursion

I keep getting a NullPointerException for the following code and I have tried and tried to trace it but to no avail. I'm trying to print out each number of a collatz conjecture which it does print out, then gives me a null pointer exception error and I can't find it.
Thanks in advance!
1 (ns collatz.core
2 (:gen-class))
3
4
5 (defn collatz [n]
6 (
7 (println n)
8 (if (= n 1)
9 (println "done")
10 (if (odd? n)
11 (collatz
12 (+(* n 3) 1))
13 (collatz (/ n 2))))))
14 (defn -main [] (collatz 48))
Exception in thread "main" java.lang.NullPointerException, compiling:(/private/var/folders/yh/80f0k44s19lgzck9bgpq746w0000gn/T/form-init1027767069879550093.clj:1:125)
at clojure.lang.Compiler.load(Compiler.java:7391)
at clojure.lang.Compiler.loadFile(Compiler.java:7317)
at clojure.main$load_script.invokeStatic(main.clj:275)
at clojure.main$init_opt.invokeStatic(main.clj:277)
at clojure.main$init_opt.invoke(main.clj:277)
at clojure.main$initialize.invokeStatic(main.clj:308)
at clojure.main$null_opt.invokeStatic(main.clj:342)
at clojure.main$null_opt.invoke(main.clj:339)
at clojure.main$main.invokeStatic(main.clj:421)
at clojure.main$main.doInvoke(main.clj:384)
at clojure.lang.RestFn.invoke(RestFn.java:421)
at clojure.lang.Var.invoke(Var.java:383)
at clojure.lang.AFn.applyToHelper(AFn.java:156)
at clojure.lang.Var.applyTo(Var.java:700)
at clojure.main.main(main.java:37)
Caused by: java.lang.NullPointerException
at collatz.core$collatz.invokeStatic(core.clj:6)
at collatz.core$collatz.invoke(core.clj:5)
at collatz.core$collatz.invokeStatic(core.clj:13)
at collatz.core$collatz.invoke(core.clj:5)
at collatz.core$collatz.invokeStatic(core.clj:13)
at collatz.core$collatz.invoke(core.clj:5)
at collatz.core$collatz.invokeStatic(core.clj:13)
at collatz.core$collatz.invoke(core.clj:5)
at collatz.core$collatz.invokeStatic(core.clj:13)
at collatz.core$collatz.invoke(core.clj:5)
at collatz.core$collatz.invokeStatic(core.clj:11)
at collatz.core$collatz.invoke(core.clj:5)
at collatz.core$collatz.invokeStatic(core.clj:13)
at collatz.core$collatz.invoke(core.clj:5)
at collatz.core$collatz.invokeStatic(core.clj:11)
at collatz.core$collatz.invoke(core.clj:5)
at collatz.core$collatz.invokeStatic(core.clj:13)
at collatz.core$collatz.invoke(core.clj:5)
at collatz.core$collatz.invokeStatic(core.clj:13)
at collatz.core$collatz.invoke(core.clj:5)
at collatz.core$collatz.invokeStatic(core.clj:13)
at collatz.core$collatz.invoke(core.clj:5)
at collatz.core$collatz.invokeStatic(core.clj:13)
at collatz.core$collatz.invoke(core.clj:5)
at collatz.core$_main.invokeStatic(core.clj:14)
at collatz.core$_main.invoke(core.clj:14)
at clojure.lang.Var.invoke(Var.java:375)
at user$eval5.invokeStatic(form-init1027767069879550093.clj:1)
at user$eval5.invoke(form-init1027767069879550093.clj:1)
at clojure.lang.Compiler.eval(Compiler.java:6927)
at clojure.lang.Compiler.eval(Compiler.java:6917)
at clojure.lang.Compiler.load(Compiler.java:7379)
... 14 more

You have (println n) in the head position (line 7), which means you attempt to invoke a function value returned by (println n). println always returns nil, so you get NullPointerException.
The minimal change is to use a do block:
(defn collatz [n]
(do
(println n)
(if (= n 1)
(println "done")
(if (odd? n)
(collatz
(+ (* n 3) 1))
(collatz (/ n 2))))))
Although frankly it looks unnatural in Clojure. A more idiomatic way of coding this would be producing a sequence instead of printing the elements out.
Additionally, I strongly suspect you have no need in gen-class. If you just need to run your function, use REPL.
Edit: As pointed out in the comments, the really minimal change would be removing the redundant parens, since defn (and fn) includes implicit do
(def collatz [n]
(println n)
(if (= n 1)
(println "done")
(if (odd? n)
(collatz
(+ (* n 3) 1))
(collatz (/ n 2)))))

Related

Where can I place the print function inside a loop/recur in Clojure?

Getting started with Clojure and functional programming. Looking at the slow example of adding numbers in a range from the not-yet-published programming Clojure book third edition, chapter 10.
How to add a println to this loop so that I can see the values of sum as they change?
; performance demo only, don't write code like this
(defn sum-to [n]
(loop [i 1 sum 0]
(if (<= i n)
(recur (inc i) (+ i sum))
sum)))
The loop macro accepts multiple body expressions, so you can insert a side-effecting println expression right before your if expression:
(defn sum-to [n]
(loop [i 1 sum 0]
(println sum)
(if (<= i n)
(recur (inc i) (+ i sum)) sum)))
Here Clojure will use the result of the last expression in the body as the return value of the whole loop expression. Example:
(sum-to 5)
;; 0
;; 1
;; 3
;; 6
;; 10
;; 15
;;=> 15
Another handy tool which in my opinions solves your problem as well but in a cleaner manner instead of printing is trace. It's extremely useful when debugging.
(use 'clojure.tools.trace)
(defn sum-to
[n]
(loop [i 1 sum 0]
(if (<= i n)
(recur (inc i) (trace (+ i sum))) sum)))
(sum-to 10)
TRACE: 1
TRACE: 3
TRACE: 6
TRACE: 10
TRACE: 15
TRACE: 21
TRACE: 28
TRACE: 36
TRACE: 45
TRACE: 55
55
Not an answer to your question, but
(reductions + (range 6))
Gives you what you’re looking for.
A handy tool I often use for this purpose is the spyx macro from the Tupelo library.
It works like so:
(ns tst.demo.core
(:use demo.core tupelo.test)
(:require
[tupelo.core :as t] ))
(t/refer-tupelo)
(defn sum-to [n]
(loop [i 1 sum 0]
(if (<= i n)
(recur (inc i) (spyx (+ i sum)))
sum)))
(spyx (sum-to 5))
with result:
(+ i sum) => 1
(+ i sum) => 3
(+ i sum) => 6
(+ i sum) => 10
(+ i sum) => 15
(sum-to 5) => 15

Clojure java.lang.Long cannot be cast to clojure.lang.IFn error

I trying to write simple factorial function in clojure, but i am getting this error:
java.lang.Long cannot be cast to clojure.lang.IFn
I know this error is usually due to an extra parenthesis, but I am not sure about this case.
First I wrote function in LISP, and it works as it should.
Code:
(defun factorial (n)
(if (= n 1)
1
(* (factorial (1- n)) n )
)
)
(factorial 5)
Then I tried it in clojure, where it doesn't work.
Clojure code:
(defn factorial [n]
(if (= n 1)
1
(* (factorial(n)) n)
)
)
(defn -main
[& args]
(println(factorial 5))
)
You've got an extra set of parens in your recursive call to factorial, probably because you meant to decrement n, it should be
(defn factorial [n]
(if (= n 1)
1
(* (factorial (dec n)) n) ;; <==
)
)
As MarkNFI showed decrementing has its own operator inc.
But to show you the problem in your code:
(defun factorial (n)
(if (= n 1)
1
(* (factorial (1- n)) n ) ;; (1- n) must be changed to (dec n) or (- n 1)
)
)
(factorial 5)
(1- n) is not the way operators in clojure work. You have to place the operator first. So in your case it would be: (- n 1)

Making current function of list recursive Clojure

Hi i am looking for a bit of help with some Clojure code. I have written a function that will take in a list and calculate the qty*price for a list eg. '(pid3 6 9)
What i am looking for is to expand my current function so that it recursively does the qty*price calculation until it reaches the end of the list.
My current function is written like this:
(defn pid-calc [list] (* (nth list 1) (nth list 2)))
I have tried implementing it into a recursive function but have had no luck at all, i want to be able to call something like this:
(pid-calcc '( (pid1 8 5) (pid2 5 6))
return==> 70
Thats as close as i have came to an answer and cannot seem to find one. If anyone can help me find a solution i that would be great. As so far i am yet to find anything that will compile.
​(defn pid-calc [list]
(if(empty? list)
nil
(* (nth list 1) (nth list 2)(+(pid-calc (rest list))))))
You don't need a recursive function. Just use + and map:
(defn pid-calc [list]
(letfn [(mul [[_ a b]] (* a b))]
(apply + (map mul list))))
#sloth's answer, suitably corrected, is a concise and fast enough way to solve your problem. It shows you a lot.
Your attempt at a recursive solution can be (a)mended to
(defn pid-calc [list]
(if (empty? list)
0
(let [x (first list)]
(+ (* (nth x 1) (nth x 2)) (pid-calc (next list))))))
This works on the example, but - being properly recursive - will run out of stack space on a long enough list. The limit is usually about 10K items.
We can get over this without being so concise as #sloth. You might find the following easier to understand:
(defn pid-calc [list]
(let [line-total (fn [item] (* (nth item 1) (nth item 2)))]
(apply + (map line-total list))))
reduce fits your scenario quite well:
(def your-list [[:x 1 2] [:x 1 3]])
(reduce #(+ %1 (* (nth %2 1) (nth %2 2))) 0 your-list)
(reduce #(+ %1 (let [[_ a b] %2] (* a b)) 0 your-list)

a recursive Fibonacci function in Clojure

I'm a newcomer to clojure who wanted to see what all the fuss is about. Figuring the best way to get a feel for it is to write some simple code, I thought I'd start with a Fibonacci function.
My first effort was:
(defn fib [x, n]
(if (< (count x) n)
(fib (conj x (+ (last x) (nth x (- (count x) 2)))) n)
x))
To use this I need to seed x with [0 1] when calling the function. My question is, without wrapping it in a separate function, is it possible to write a single function that only takes the number of elements to return?
Doing some reading around led me to some better ways of achieving the same funcionality:
(defn fib2 [n]
(loop [ x [0 1]]
(if (< (count x) n)
(recur (conj x (+ (last x) (nth x (- (count x) 2)))))
x)))
and
(defn fib3 [n]
(take n
(map first (iterate (fn [[a b]] [b (+ a b)]) [0 1]))))
Anyway, more for the sake of the exercise than anything else, can anyone help me with a better version of a purely recursive Fibonacci function? Or perhaps share a better/different function?
To answer you first question:
(defn fib
([n]
(fib [0 1] n))
([x, n]
(if (< (count x) n)
(fib (conj x (+ (last x) (nth x (- (count x) 2)))) n)
x)))
This type of function definition is called multi-arity function definition. You can learn more about it here: http://clojure.org/functional_programming
As for a better Fib function, I think your fib3 function is quite awesome and shows off a lot of functional programming concepts.
This is fast and cool:
(def fib (lazy-cat [0 1] (map + fib (rest fib))))
from:
http://squirrel.pl/blog/2010/07/26/corecursion-in-clojure/
In Clojure it's actually advisable to avoid recursion and instead use the loop and recur special forms. This turns what looks like a recursive process into an iterative one, avoiding stack overflows and improving performance.
Here's an example of how you'd implement a Fibonacci sequence with this technique:
(defn fib [n]
(loop [fib-nums [0 1]]
(if (>= (count fib-nums) n)
(subvec fib-nums 0 n)
(let [[n1 n2] (reverse fib-nums)]
(recur (conj fib-nums (+ n1 n2)))))))
The loop construct takes a series of bindings, which provide initial values, and one or more body forms. In any of these body forms, a call to recur will cause the loop to be called recursively with the provided arguments.
You can use the thrush operator to clean up #3 a bit (depending on who you ask; some people love this style, some hate it; I'm just pointing out it's an option):
(defn fib [n]
(->> [0 1]
(iterate (fn [[a b]] [b (+ a b)]))
(map first)
(take n)))
That said, I'd probably extract the (take n) and just have the fib function be a lazy infinite sequence.
(def fib
(->> [0 1]
(iterate (fn [[a b]] [b (+ a b)]))
(map first)))
;;usage
(take 10 fib)
;;output (0 1 1 2 3 5 8 13 21 34)
(nth fib 9)
;; output 34
A good recursive definition is:
(def fib
(memoize
(fn [x]
(if (< x 2) 1
(+ (fib (dec (dec x))) (fib (dec x)))))))
This will return a specific term. Expanding this to return first n terms is trivial:
(take n (map fib (iterate inc 0)))
Here is the shortest recursive function I've come up with for computing the nth Fibonacci number:
(defn fib-nth [n] (if (< n 2)
n
(+ (fib-nth (- n 1)) (fib-nth (- n 2)))))
However, the solution with loop/recursion should be faster for all but the first few values of 'n' since Clojure does tail-end optimization on loop/recur.
this is my approach
(defn fibonacci-seq [n]
(cond
(= n 0) 0
(= n 1) 1
:else (+ (fibonacci-seq (- n 1)) (fibonacci-seq (- n 2)))
)
)
For latecomers. Accepted answer is a slightly complicated expression of this:
(defn fib
([n]
(fib [0 1] n))
([x, n]
(if (< (count x) n)
(recur (conj x (apply + (take-last 2 x))) n)
x)))
For what it's worth, lo these years hence, here's my solution to 4Closure Problem #26: Fibonacci Sequence
(fn [x]
(loop [i '(1 1)]
(if (= x (count i))
(reverse i)
(recur
(conj i (apply + (take 2 i)))))))
I don't, by any means, think this is the optimal or most idiomatic approach. The whole reason I'm going through the exercises at 4Clojure ... and mulling over code examples from Rosetta Code is to learn clojure.
Incidentally I'm well aware that the Fibonacci sequence formally includes 0 ... that this example should loop [i '(1 0)] ... but that wouldn't match their spec. nor pass their unit tests despite how they've labelled this exercise. It is written as an anonymous recursive function in order to conform to the requirements for the 4Clojure exercises ... where you have to "fill in the blank" within a given expression. (I'm finding the whole notion of anonymous recursion to be a bit of a mind bender; I get that the (loop ... (recur ... special form is constrained to tail-recursion ... but it's still a weird syntax to me).
I'll take #[Arthur Ulfeldt]'s comment, regarding fib3 in the original posting, under consideration as well. I've only used Clojure's iterate once, so far.

How to make a recursive function local to the let body

I'm trying to make a function in Clojure that is local to the body of a (let ...) function. I tried the following, but (defn ...) defines things in the global namespace.
(let [] (defn power [base exp]
(if (= exp 0)
1
(if (> exp 0)
; Exponent greater than 0
(* base (power base (- exp 1)))
; Exponent less than 0
(/ (power base (+ exp 1)) base))))
(println (power -2 3)))
; Function call outside of let body
(println (power -2 3))
Now, I also tried:
(let [power (fn [base exp]
(if (= exp 0)
1
(if (> exp 0)
; Exponent greater than 0
(* base (power base (- exp 1)))
; Exponent less than 0
(/ (power base (+ exp 1)) base))))]
(println (power -2 3)))
; Function call outside of let body
(println (power -2 3))
But then I get the error:
Exception in thread "main" java.lang.Exception: Unable to resolve symbol: power in this context (math.clj:6)
How do I make a function whose namespace is local to the let body and can recursively call itself?
For this you can use letfn:
(letfn [(power [base exp]
(cond
(= exp 0)
1
(> exp 0) ; Exponent greater than 0
(* base (power base (dec exp)))
:else ; Exponent less than 0
(/ (power base (inc exp)) base)))]
(print (power -2 3)))
Note that I also changed your nested if-construction to cond, I think it is more readable. Also I changed (+ exp 1) and (- exp 1) to (inc exp) and (dec exp) respectively. You can even improve your function more like using recur and an accumulator argument, but maybe that goes beyond the scope of your question. Also see Brian Carper's comment below.
letfn is the best solution for your particular case. However, you can also created a named "anonymous" function like so:
(let [power (fn power [base exp] ...)]
(println (power -2 3)))
However, this style doesn't allow for mutually recursive functions, which letfn does.
Besides to good answer of Michel: Using high order function on lazy sequences often allow consise solutions compared to explicit recursion:
(defn power [base exp]
(reduce * (repeat exp base)))
Here is a solution which is an example of Michiel's last statement about using an accumulator. This lets you use recur to gain advantage of tail call optimization. This gives you the advantage of not consuming stack space with each recursion.
(defn pow [base exp]
(letfn [(power [base exp accum]
(cond
(= exp 0) accum
(> exp 0) (recur base (dec exp) (* accum base))
:else (recur base (inc exp) (/ accum base))))]
(power base exp 1)))
user> (pow -3 2)
9
user> (pow -3 3)
-27
If you are simply looking to write a function which does raises a base number to a power don't forget you can call out to methods which already exist in Java. java.util.Math can help you out here.
(Math/pow -2 3)

Resources