I'm new to clojure and messing around in the repl.
I've noticed that I'm getting expected results with the rem function.
So without clojure if I do 8/5 = 1.6
user=> (quot 8 5)
1
as expected
user=> (rem 8 5)
3
Why am I getting 3? I was kind of expecting a 6. Am I missing something here?
The function you want for what you imagined rem to be:
(defn frac [x y] (let [r (rem x y)] (double (/ r y))))
user> (frac 8 5)
0.6
rem gives you the remainder of indeger division of 8 by 5 (since 8 = 5 * 1 + 3)
So what you're getting is correct. Why would you expect 6 there?
Related
I have this curious demonstration of partials. Here is the code:
Start by declaring a vector and a partial. As expected, reduce and apply sums the integers on vector a:
> (def a [1 2 3 4 5])
> (def p (partial + 10))
> (apply + a)
15
> (reduce + a)
15
Now, using apply on the partial p and vector a, I'm getting the sum of a and the +10 from the partial, which makes sense:
> (apply p a)
25
Now, using (reduce) makes no sense to me. Where is 55 coming from?
> (reduce p a)
55
The closest I can come up with is, (reduce) version is adding 10 from the 1 index and ignoring the zero index before adding everything together:
> (+ (first a) (reduce + (map #(+ % 10) (rest a))))
55
I'm just curious if anyone knows what is happening here, exactly? I don't really know what answer I'm expecting with this, but I also don't understand what is happening either. I have no idea why I would get 55 as an answer.
The first thing to note is that + is variadic: it can be called with zero, one, two, or more arguments. When you do (apply + a) you are essentially calling + with five arguments and getting the sum back (15).
However, reduce treats the function as strictly binary and calls it repeatedly, with the result of the previous call as the first argument of the next call. (reduce + a) is (+ (+ (+ (+ 1 2) 3) 4) 5) which also happens to be 15.
So your partial is also variadic and can be called with five arguments, as in the apply call: (apply p a) = (p 1 2 3 4 5) = (+ 10 1 2 3 4 5) so you get 25.
The reduce on p is going to call it repeatedly as shown above, but this time the function adds 10 in each time: (reduce p a) = (p (p (p (p 1 2) 3) 4) 5) = (+ 10 (+ 10 (+ 10 (+ 10 1 2) 3) 4) 5) so you get four 10s and the 15 making 55.
Another way of looking at Sean Corfield's fine answer:
Given
(def p (partial + 10))
then (p x y) means (+ 10 x y), for any x and y.
So
(reduce p a)
means
(reduce (fn [x y] (+ 10 x y)) a)
... since the first argument to reduce is a function of two arguments.
No initial value is supplied, so (first a) is used as such, and the reduction is applied to (rest a), which has four elements.
All the elements of a get added in: the first as the initial value;
the others by reduction.
The 10 gets added on in every cycle of the reduction: four times.
So the final result is the same as
(+ (* 10 (dec (count a))) (reduce + a))
In this case, 55.
I assume this is a very simple question, but I can't seem to find the answer online: how do you subtract n from every element of a Clojure sequence? E.g subtract 4 from each element of (6 9 11) and get (2 5 7)?
I assume this should be done with map, and I know that for the special case of subtracting 1 I can do (map dec (sequence)), but how do I do it for any other case?
For what it's worth, I figured out eventually that (map - (map (partial - n) (sequence)) technically does work, but it's clearly not how this is meant to be done.
For anyone who lands here from search and has a slightly different problem: if you want to subtract every element of a Clojure sequence from n, you can do that with (map (partial - n) (sequence))
Similarly, for multiplying every element of a Clojure sequence by n you can do (map (partial * n) (sequence))
For adding n to every element of a Clojure sequence (map (partial + n) (sequence))
I found that answer in these Clojure docs so I assume it's idiomatic, but obviously I'm not able to vouch for that myself.
An anonymous function literal is convenient here:
> (map #(- % 4) [6 9 11])
(2 5 7)
The #(- % 4) form is short-hand for the anonymous function in
> (map (fn [x] (- x 4)) [6 9 11])
(2 5 7)
If you're looking for a combinatory expression for the function you want, try (comp - (partial - 4)):
=> (map (comp - (partial - 4)) '(6 9 11))
(2 5 7)
Remember that + and - are just ordinary named Clojure functions. The function that you need is probably not worth naming, so you express it directly as #(- % 4) or (fn [n] (- n 4)), or as above.
It is also worth remembering that map is lazy, so can deal with endless sequences:
=> (take 10 (map (comp - (partial - 4)) (range)))
(-4 -3 -2 -1 0 1 2 3 4 5)
This can be achieved through maps. Clojure maps takes a function and list as an argument.
Synatax:
(map (function) (seq))
test=> (map (fn[arg] (- arg 4) ) '(7 8 9) )
(3 4 5)
test=> (map (fn[arg] (- arg 4) ) [7 8 9] )
(3 4 5)
Map can take function in shorthand notation too.
(- % 4)
. Here % is argument passed. Defaults to first argument. %1 to explicitly say first argument
test=> (map #(- %1 4) [7 8 9])
(3 4 5)
test=> (map #(- % 4) [7 8 9])
(3 4 5)
Hi I am programming in clojure and though the problem of modulo inverse has nothing to do with language i am stuck at this code -
(defn EulerDiv [x p]
(let [ToMod (+ p 2)]
(loop [num 1 toPow (int p) numDouble x]
(if (= 0 toPow)
num
(let [numDouble2 (rem (* numDouble numDouble) ToMod)
halfToPow (int (/ toPow 2))]
(if (odd? toPow)
(recur (rem (* num numDouble) ToMod)
halfToPow
numDouble2)
(recur num halfToPow numDouble2))
))))
)
It seems to give me right answers for small Primes but when i am using it in a problem with Bigger primes i am getting answers other than result like :
(= 2 (mod (* 4 (EulerDiv 2 (- 3 2))) 3))
This prints true
(def ToMod (+ 10e8 7))
( = 1 (int (mod (* 2 (EulerDiv 2 (- ToMod 2))) ToMod)) )
This prints false.
Also there is rem and mod in clojure.
mod makes the output positive and hence i can not use it in between the calculations.
It is a programming contest but this is just part of solution and this info of modulo inverse was also provided in the problem page.
The problem is that of programming calculator grammar for evaluating evpressions like 4/-2/(2 + 8)
You are straying from integer arithmetic.
Given integers, the / function can produce rationals: (/ 1 2) is 1/2, not 0.
And 1e9 is 1.0E9, a double, not an integer.
There are appropriate substitutes available. Look at the arithmetic section here for an integer division function, and at the cast section for something to convert a number to an integer.
All the best!
I wrote this code to nest a function n times and am trying to extend the code to handle a test. Once the test returns nil the loop is stopped. The output be a vector containing elements that tested true. Is it simplest to add a while loop in this case? Here is a sample of what I've written:
(defn nester [a inter f]
(loop [level inter expr a]
(if (= level 0) expr
(if (> level 0) (recur (dec level) (f expr))))))
An example input would be an integer 2, and I want to nest the inc function until the output is great than 6. The output should be [2 3 4 5 6 7].
(defn nester [a inter f test-fn]
(loop [level inter
expr a]
(if (or (zero? level)
(nil? (test-fn expr)))
expr
(recur (dec level)
(f expr)))))
If you also accept false (additionally to nil) from your test-fn, you could compose this more lazily:
(defn nester [a inter f test-fn]
(->> (iterate f a)
(take (inc inter))
(drop-while test-fn)
first))
EDIT: The above was answered to your initial question. Now that you have specified completely changed the meaning of your question:
If you want to generate a vector of all iterations of a function f over a value n with a predicate p:
(defn nester [f n p]
(->> (iterate f n)
(take-while p)
vec))
(nester inc 2 (partial > 8)) ;; predicate "until the output is greater than six"
;; translated to "as long as 8 is greater than
;; the output"
=> [2 3 4 5 6 7]
To "nest" or iterate a function over a value, Clojure has the iterate function. For example, (iterate inc 2) can be thought of as an infinite lazy list [2, (inc 2), (inc (inc 2)), (inc (inc (inc 2))) ...] (I use the [] brackets not to denote a "list"--in fact, they represent a "vector" in Clojure terms--but to avoid confusion with () which can denote a data list or an s-expression that is supposed to be a function call--iterate does not return a vector). Of course, you probably don't want an infinite list, which is where the lazy part comes in. A lazy list will only give you what you ask it for. So if you ask for the first ten elements, that's what you get:
user> (take 10 (iterate inc 2))
> (2 3 4 5 6 7 8 9 10 11)
Of course, you could try to ask for the whole list, but be prepared to either restart your REPL, or dispatch in a separate thread, because this call will never end:
user> (iterate inc 2)
> (2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
=== Shutting down REPL ===
=== Starting new REPL at C:\Users\Omnomnomri\Clojure\user ===
Clojure 1.5.0
user>
Here, I'm using clooj, and this is what it looks like when I restart my REPL. Anyways, that's all just a tangent. The point is that iterate answers the core of your question. The other part, stopping upon some test condition, involves take-while. As you might imagine, take-while is a lot like take, only instead of stopping after some number of elements, it stops upon some test condition (or in Clojure parlance, a predicate):
user> (take-while #(< % 10) (iterate inc 2))
> (2 3 4 5 6 7 8 9)
Note that take-while is exclusive with its predicate test, so that here once the value fails the test (of being less than 10), it excludes that value, and only includes the previous values in the return result. At this point, solving your example is pretty straightfoward:
user> (take-while #(< % 7) (iterate inc 2))
> (2 3 4 5 6)
And if you need it to be a vector, wrap the whole thing in a call to vec:
user> (vec (take-while #(< % 7) (iterate inc 2)))
> [2 3 4 5 6]
I'm trying to touch all potential dealer hands in blackjack, but when I kept blowing the stack, I realized things weren't as depth first as expected. So I tried similar code in ruby and it performed differently.
this code,
(def d [2 3 4 5 6 7 8 9 10 10 10 10 11])
(defn dig1 [lst depth tot]
(do
(print depth)
(if (< tot 17) (map #(dig1 (conj lst %) (+ depth 1) (+ tot %)) d)) ))
(dig1 [0] 0 0)
produces: 011111111111112222222222222...
I expected map to execute the function on d[0] and dig down rather than to see everything executed at a given level. I obviously don't understand what's going on. Do I need to make something lazy(er)? map produces lazy sequences, but apparently chunks them in groups of 32.
in contrast,
#d = [2,3,4,5,6,7,8,9,10,10,10,10,11]
def dig(lst, depth, tot)
p depth
#d.map{|e| dig(lst.dup.push(e),depth+1,tot+e)} if tot < 17
end
produces what I would expect: 0123456789999999999999888888888888
If anyone could tell me how to make the clojure output look like the ruby output, I'd appreciate it.
Thanks, John
Generally map isn't used when you don't want the returned values back and are only evaluating the sequence for side effects. Something like doseq is preferable.
(def d [2 3 4 5 6 7 8 9 10 10 10 10 11])
(defn dig1 [lst depth tot]
(print depth)
(when (< tot 17)
(doseq [i d]
(dig1 (conj lst i)
(inc depth)
(+ tot i)))))
(dig1 [0] 0 0)
Produces: 012345678999....