I'm working through Clojure Koans and I'm up to the recursion koans.
I don't understand how to solve is-even? using recursion. The exercise partially defines this function as:
(defn is-even? [n]
(if (= n 0)
true
(__ (is-even? (dec n)))))
If I don't want to use recursion then I would define it as (defn is-even? [n] (= (mod n 2) 0)) but that goes against the point of the exercise.
Like amalloy said, fill the blanks with "not". But provided you assume the argument can only be 0 or positive, you don't need another base case: dec makes sure you always end up at 0, and odd numbers return false like this:
(is-even? 0) ==> base case (= 0 0) ==> true.
(is-even? 1) ==> (not (is-even? (dec 1))
==> (not (is-even? 0))
==> (not true)
==> false
(is-even? 2) ==> (not (is-even? 1))
==> (not false)
==> true
etcetera.
A number n is even if either:
n is 0
n-1 is NOT even
So really, not should be enough to fill in that blank. Eventually you wind up with N nots around (= 0 0), and most of them cancel out.
Consider decrementing by 2 for each recursion. The rest should be obvious: The number is even only if the function ends up with zero.
EDIT: Apparently I missed the memo about filling in the blank. Here is the tail call optimizable solution I had in mind for positive integers:
(defn is-even? [n]
(if (<= n 1)
(= n 0)
(is-even? (- n 2))))
Related
I'm trying to get the hang of recursion in scheme. I put together a Fibinachi function and it keeps returning unspecified instead of a number. How do I make this function return a number and to unspecified?
(define (F n)
(if (= n 0)
0)
(if (= n 1)
1)
(if (< n 2)
(+
(F (- n 1))
(F (- n 2)))))
(display (F 5))
(newline)
The function returns
#<unspecified>
I'm using guile (GNU Guile) 2.0.13.
The issue here is that your code is:
(begin
(if a 1)
(if b 2)
(if c 3))
What is wrong with this? The value of that will be unspecified except if c is true.
Why? The value of each if is unspecified when the condition is false. The begin returns the value of the last expression.
Where did the begin come from you might ask as it didn't appear in my code? To make it easier every lambda and define contains an implicit begin which is why your code was even accepted for execution.
You should use either nested ifs or a cond form:
(if a 1
(if b 2
(if c 3)))
(cond (a 1)
(b 2)
(c 3))
Im dealing with recursion in clojure, which i dont really understand.
I made a small program taked from here that tries to find the smalles number that can be divided by all the numbers from 1 to 20. This is the code i wrotte, but there must be something im missing because it does not work.
Could you give me a hand? thanks!
(defn smallest [nume index]
(while(not ( = index 0))
(do
(cond
(zero?(mod nume index))(let [dec' index] (smallest nume index))
:else (let [inc' nume] (smallest nume index))))))
EDIT:
Looks like is better loop/recur so i tried it:
(loop [nume 20
index 20]
(if (= index 0)
(println nume)
(if (zero?(mod nume index))
(recur nume (dec index))
(recur (inc nume) 20)))))
Working. If you are curious about result--> 232792560
while does not do what you think it does.
In clojure, everything (well, almost) is immutable, meaning that if index is 0, it will always be 0 in the same context. Thus looping until it is 1 makes little sense.
There are a number of ways to achieve what you are trying to do, the first, and most trivial (I think!) to newcomers, is to understand loop/recur. So for example:
(loop [counter 0]
(when (< counter 10)
(println counter)
(recur (inc counter))))
In here, counter is defined to be 0, and it never changes in the usual way. When you hit recur, you submit a new value, in this case the increment of the previous counter, into a brand new iteration starting at loop, only now counter will be bound to 1.
Edit: Notice however, that this example will always return nil. It is only used for the side effect of println. Why does it return nil? Because in the last iteration, the when clause will return nil. If you want to return something else, you should perhaps use if and specify what would you like to be returned at the last iteration.
You should read a little more about this paradigm, and perhaps do exercises like 4clojure to get a better grasp at this. Once you do, it will become MUCH simpler for you to think in this way, and the tremendous benefits of this style will begin to emerge.
Good luck!
Here's a brute force implementation testing all numbers on the condition if they can be divided by all numbers from 1 to 10 (please note (range 1 11)) in the code:
(first
(filter #(second %)
(map (fn[x] [x (every? identity
(map #(= 0 (mod x %))
(range 2 11)))])
(range 1 Integer/MAX_VALUE))))
It's output is
[2520 true]
Unfortunately, this is not a good approach for bigger numbers. With (range 1 21) it doesn't finish after few minutes of waiting on my Macbook. Let's try this:
user=> (defn gcd [a b] (if (zero? b) a (recur b (mod a b))))
#'user/gcd
user=> (reduce (fn[acc n] (if (not= 0 (mod acc n)) (* acc (/ n (gcd n acc))) acc)) 1 (range 1 11))
2520
user=> (reduce (fn[acc n] (if (not= 0 (mod acc n)) (* acc (/ n (gcd n acc))) acc)) 1 (range 1 21))
232792560
I'm new to the racket programming language so as a quick test, I typed this up on DrRacket:
>(define (test k)
(when (not (= k 0))
(begin
k
(test (- k 1)))))
>(test 5)
I expected an output of:
54321
but instead got nothing in return...
Tried an alternate approach:
>(define (test k)
(when (not (= k 0))
(begin
(test (- k 1)) k)))
>(test 5)
but this only printed the number 5. I'm not sure what's going on. What am I doing wrong? Any help is greatly appreciated and thank you so much in advance!
You have to explicitly print the value if you want it to be shown on the console, otherwise the line with the k is doing nothing - remember, Scheme is at its core a functional programming language, and a conditional returns the value of the last expression, all the others are just executed for the effect, but don't return a value. A couple of tips:
(define (test k)
(unless (zero? k) ; use unless instead of when-not, zero? instead of (= x 0)
(display k) ; display prints in console
(test (sub1 k)))) ; use sub1 instead of (- x 1)
Just tried a different approach and that seemed to yield results:
> (define (prnt k) k)
> (define (test k)
(when (not (= k 0))
(begin
(print k)
(test (- k 1)))))
> (test 5)
This printed 54321 which is the behavior I expected. Not too sure why this works but previous attempts didn't but if anyone could shed light on the topic, that would be greatly appreciated!
I am still new in racket language.
I am implementing a switch case in racket but it is not working.
So, I shift into using the equal and condition. I want to know how can i call a function that takes input. for example: factorial(n) function
I want to call it in :
(if (= c 1) (factorial (n))
There are two syntax problems with this snippet:
(if (= c 1) (factorial (n)))
For starters, an if expression in Racket needs three parts:
(if <condition> <consequent> <alternative>)
The first thing to fix would be to provide an expression that will be executed when c equals 1, and another that will run if c is not equal to 1. Say, something like this:
(if (= c 1) 1 (factorial (n)))
Now the second problem: in Scheme, when you surround a symbol with parentheses it means that you're trying to execute a function. So if you write (n), the interpreter believes that n is a function with no arguments and that you're trying to call it. To fix this, simply remove the () around n:
(if (= c 1) 1 (factorial n))
Now that the syntax problems are out of the way, let's examine the logic. In Scheme, we normally use recursion to express solutions, but a recursion has to advance at some point, so it will eventually end. If you keep passing the same parameter to the recursion, without modifying it, you'll get caught in an infinite loop. Here's the proper way to write a recursive factorial procedure:
(define (factorial n)
(if (<= n 0) ; base case: if n <= 0
1 ; then return 1
(* n (factorial (- n 1))))) ; otherwise multiply and advance recursion
Notice how we decrement n at each step, to make sure that it will eventually reach zero, ending the recursion. Once you get comfortable with this solution, we can think of making it better. Read about tail recursion, see how the compiler will optimize our loops as long as we write them in such a way that the last thing done on each execution path is the recursive call, with nothing left to do after it. For instance, the previous code can be written more efficiently as follows, and see how we pass the accumulated answer in a parameter:
(define (factorial n)
(let loop ([n n] [acc 1])
(if (<= n 0)
acc
(loop (- n 1) (* n acc)))))
UPDATE
After taking a look at the comments, I see that you want to implement a switchcase procedure. Once again, there are problems with the way you're declaring functions. This is wrong:
(define fact(x)
The correct way is this:
(define (fact x)
And for actually implementing switchcase, it's possible to use nested ifs as you attempted, but that's not the best way. Learn how to use the cond expression or the case expression, either one will make your solution simpler. And anyway you have to provide an additional condition, in case c is neither 1 nor 2. Also, you're confounding the parameter name - is it c or x? With all the recommendations in place, here's how your code should look:
(define (switchcase c)
(cond ((= c 1) (fact c))
((= c 2) (triple c))
(else (error "unknown value" c))))
In racket-lang, conditionals with if has syntax:
(if <expr> <expr> <expr>)
So in your case, you have to provide another <expr>.
(define (factorial n)
(if (= n 1) 1 (* n (factorial (- n 1)))))
;^exp ^exp ^exp
(factorial 3)
The results would be 6
Update:
(define (factorial n)
(if (= n 1) 1 (* n (factorial (- n 1)))))
(define (triple x)
(* 3 x))
(define (switchcase c)
(if (= c 1)
(factorial c)
(if(= c 2)
(triple c) "c is not 1 or 2")))
(switchcase 2)
If you want something a lot closer to a switch case given you can return procedures.
(define (switch input cases)
(let ((lookup (assoc input cases)))
(if lookup
(cdr lookup)
(error "Undefined case on " input " in " cases))))
(define (this-switch c)
(let ((cases (list (cons 1 triple)
(cons 2 factorial))))
((switch c cases) c)))
What am I doing wrong? Simple recursion a few thousand calls deep throws a StackOverflowError.
If the limit of Clojure recursions is so low, how can I rely on it?
(defn fact[x]
(if (<= x 1) 1 (* x (fact (- x 1)) )))
user=> (fact 2)
2
user=> (fact 4)
24
user=> (fact 4000)
java.lang.StackOverflowError (NO_SOURCE_FILE:0)
Here's another way:
(defn factorial [n]
(reduce * (range 1 (inc n))))
This won't blow the stack because range returns a lazy seq, and reduce walks across the seq without holding onto the head.
reduce makes use of chunked seqs if it can, so this can actually perform better than using recur yourself. Using Siddhartha Reddy's recur-based version and this reduce-based version:
user> (time (do (factorial-recur 20000) nil))
"Elapsed time: 2905.910426 msecs"
nil
user> (time (do (factorial-reduce 20000) nil))
"Elapsed time: 2647.277182 msecs"
nil
Just a slight difference. I like to leave my recurring to map and reduce and friends, which are more readable and explicit, and use recur internally a bit more elegantly than I'm likely to do by hand. There are times when you need to recur manually, but not that many in my experience.
The stack size, I understand, depends on the JVM you are using as well as the platform. If you are using the Sun JVM, you can use the -Xss and -XThreadStackSize parameters to set the stack size.
The preferred way to do recursion in Clojure though is to use loop/recur:
(defn fact [x]
(loop [n x f 1]
(if (= n 1)
f
(recur (dec n) (* f n)))))
Clojure will do tail-call optimization for this; that ensures that you’ll never run into StackOverflowErrors.
And due defn implies a loop binding, you could omit the loop expression, and use its arguments as the function argument. And to make it a 1 argument function, use the multiary caracteristic of functions:
(defn fact
([n] (fact n 1))
([n f]
(if (<= n 1)
f
(recur (dec n) (* f n)))))
Edit: For the record, here is a Clojure function that returns a lazy sequence of all the factorials:
(defn factorials []
(letfn [(factorial-seq [n fact]
(lazy-seq
(cons fact (factorial-seq (inc n) (* (inc n) fact)))))]
(factorial-seq 1 1)))
(take 5 (factorials)) ; will return (1 2 6 24 120)
Clojure has several ways of busting recursion
explicit tail calls with recur. (they must be truely tail calls so this wont work)
Lazy sequences as mentioned above.
trampolining where you return a function that does the work instead of doing it directly and then call a trampoline function that repeatedly calls its result until it turnes into a real value instead of a function.
(defn fact ([x] (trampoline (fact (dec x) x)))
([x a] (if (<= x 1) a #(fact (dec x) (*' x a)))))
(fact 42)
620448401733239439360000N
memoizing the the case of fact this can really shorten the stack depth, though it is not generally applicable.
ps: I dont have a repl on me so would someone kindly test-fix the trapoline fact function?
As I was about to post the following, I see that it's almost the same as the Scheme example posted by JasonTrue... Anyway, here's an implementation in Clojure:
user=> (defn fact[x]
((fn [n so_far]
(if (<= n 1)
so_far
(recur (dec n) (* so_far n)))) x 1))
#'user/fact
user=> (fact 0)
1
user=> (fact 1)
1
user=> (fact 2)
2
user=> (fact 3)
6
user=> (fact 4)
24
user=> (fact 5)
120
etc.
As l0st3d suggested, consider using recur or lazy-seq.
Also, try to make your sequence lazy by building it using the built-in sequence forms as a opposed to doing it directly.
Here's an example of using the built-in sequence forms to create a lazy Fibonacci sequence (from the Programming Clojure book):
(defn fibo []
(map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))
=> (take 5 (fibo))
(0 1 1 2 3)
The stack depth is a small annoyance (yet configurable), but even in a language with tail recursion like Scheme or F# you'd eventually run out of stack space with your code.
As far as I can tell, your code is unlikely to be tail recursion optimized even in an environment that supports tail recursion transparently. You would want to look at a continuation-passing style to minimize stack depth.
Here's a canonical example in Scheme from Wikipedia, which could be translated to Clojure, F# or another functional language without much trouble:
(define factorial
(lambda (n)
(let fact ([i n] [acc 1])
(if (zero? i)
acc
(fact (- i 1) (* acc i))))))
Another, simple recursive implementation simple could be this:
(defn fac [x]
"Returns the factorial of x"
(if-not (zero? x) (* x (fac (- x 1))) 1))
To add to Siddhartha Reddy's answer, you can also borrow the Factorial function form Structure And Interpretation of Computer Programs, with some Clojure-specific tweaks. This gave me pretty good performance even for very large factorial calculations.
(defn fac [n]
((fn [product counter max-count]
(if (> counter max-count)
product
(recur (apply *' [counter product])
(inc counter)
max-count)))
1 1 n))
Factorial numbers are by their nature very big. I'm not sure how Clojure deals with this (but I do see it works with java), but any implementation that does not use big numbers will overflow very fast.
Edit: This is without taking into consideration the fact that you are using recursion for this, which is also likely to use up resources.
Edit x2: If the implementation is using big numbers, which, as far as I know, are usually arrays, coupled with recursion (one big number copy per function entry, always saved on the stack due to the function calls) would explain a stack overflow. Try doing it in a for loop to see if that is the problem.