Implementation of Newton's Method in Clojure - clojure

I'm trying to implement Newton's Method in clojure to solve the equation f(x)=0. Function takes these arguments: f(function) f'(function's derivative) n(# of iterations)=10 and x0(initial guess)=10.
(defn newtons-method [f f' n x0]
(if (<= (f x0))
n
(newtons-method f f' (- x0 (/ (f x0) (f' x0))) (+ n 1)))
)
I'm getting an output of 10, but instead want the final solution of x and result of f(x) and I know 10 is wrong, because my function f and its derivative give the correct answer, so I assume I'm messing up somewhere in the iterations

Well, you seem to have at least two issues.
Firstly, your conditional will always return true (assuming (f x0) returns a numeric value), so that is likely not what you want to do.
Also, in order to properly implement recursive functions in clojure, you should have a look at recur, otherwise you could run into stack overflows (unlikely in this particular case, but still)
Another minor thing, instead of doing (+ n 1), it's idiomatic to use (inc n)

Related

I need help to understand a lisp program that finds the depth of a list

I need help to understand my code theoretically. Here is my lisp program:
(defun depth (lst)
(if (or (null lst) (atom lst)) 0
(+ 1 (apply 'max (mapcar #'depth lst)))
))
I know it works with this example:
(write (depth '((a (b c) d r ((t))))) -> 3
I just can't understand the else statement of the IF statement that I tried.
If you can help me, it will be very much appreciated. Thank you in advance.
Here is your code, slightly reformatted:
(defun depth (value)
(if (or (null value) (atom value))
0
(+ 1 (apply 'max (mapcar #'depth value)))))
I renamed lst (you could have written it list, by the way) to value, because the name is confusing as it suggest that the variable is always a list, which is not true. The function depth can be called on any value:
(depth "hello")
=> 0
(depth 100)
=> 0
The then branch of the if is evaluated when value is NIL or any atom. Since NIL is also an atom, the test expression could be simplified as (atom value). When value is an atom, the depth is zero.
The else branch of the if is evaluated when value is not an atom, which by definition of atom means value here is a cons. The function also assumes that it is a proper list, and not some circular list.
Since value is a list in that branch, we can call mapcar on it: (mapcar #'depth value); this is where the function assumes the list is proper.
This computes (depth v) for each v in value. More precisely if value is a list of length n, then that call to mapcar evaluates as a list of numbers (D1 ... Dn) where Di is (depth Vi) for all i between 1 and n.
So we know that (apply 'max (mapcar ...)) is (apply 'max depths) for some list depths of numbers. In general:
(apply fn v1 ... vn list)
... is a way to call the function object denoted by the fn expression with at least n elements (v1 to vn), as well as an arbitrary number of additional elements stored in list. When you quote the function, as 'max, or when you write #'max, you refer to a function by its name in the function namespace.
Contrast this to the usual way of calling a function:
(f x y z)
The function name and the number of arguments being passed is fixed: as soon the form is read we knows there is a call to f with 3 arguments.
The apply function is a built-in that allows you to pass additional arguments in a list, in the last call argument. The above call could be written:
(apply #'f x y z ()) ;; note the empty list as a last argument
This could also be written:
(apply #'f (list x y z)) ;; all arguments in the last list
The only difference is probably a matter of runtime efficiency (and with good compilers, maybe there is no difference).
In your example, you do:
(apply max depths)
Which would be the same as writing (pseudo-code):
(max d1 d2 d3 ... dn)
... where depths is the list (list d1 d2 ... dn).
But we can't literally write them all directly, since the content of the list is only known at runtime.
Thus, the call to apply computes the max depths among all the depths computed recursively. Note that the above is a somewhat improper use of apply, since apply should not be called with lists of arbitrary size: there is a limit in the standard named CALL-ARGUMENTS-LIMIT that is allowed to be as low as 50 in theory, the maximum size of such a list (we will see an alternative below).
Finally, depth evaluates (+ 1 ...) on this result. In other words, the whole expression can be summarized as: the depth of a list is 1 added to the maximum depth of all its elements.
Using reduce
Instead of apply, you can use REDUCE to compute max successively on a list. This is preferable to apply because:
there is no limitation for the number of elements, like apply
(reduce 'max depths) ;; works the same, but more reliably
there is no need need to build an intermediate list of depths, you iterate over the list of values, call depth and directly use the result to compute the max. The skeleton is:
(reduce (lambda (max-so-far item) ...)
value
:initial-value 0)
Declarative approach
Instead of reduce, the loop macro can be used as a more readable alternative to express the same computation. I also use typecase which in my opinion makes the intent clearer:
(defun depth (value)
(typecase value
(atom 0)
(cons (1+ (loop for v in value maximize (depth v))))))

Prevent Clojure from simplifying ratios

Is there any way to prevent clojure from making for example a 2/5 from 6/15? I need for a function to have the original denominators of ratios, hence the question.
There is no way to prevent clojure from making 2/5 from 6/15. This is most readily apparent from the equality of clojure.lang.Ratio defined here. Preserving the original unreduced version would break equality.
This sounds like a datatype problem. You are putting information into a type that doesn't preserve the amount of data that you need. Fundamentally you are putting two numbers into a ratio datatype which is a single scalar value. You'll (most probably) need to thread more information through or delay the conversion into a ratio.
The calculation of GCD is not conditional:
https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/Numbers.java#L355
You can create a clojure.lang.Ratio type directly:
user=> (def x (clojure.lang.Ratio.
(java.math.BigInteger. "6") (java.math.BigInteger. "15")))
user=> (type x)
clojure.lang.Ratio
user=> x
6/15
But compareTo assumes the reduction has occurred and checks the numerator and denominator values individually:
user=> (def y (/ 6 15))
#'user/y
user=> (type y)
clojure.lang.Ratio
user=> y
2/5
user=> (= x y)
false
And other operations will wind up reducing:
user=> (* 3 x)
6/5
user=> (* 3 y)
6/5
Strange requirement. A simple solution is NOT to calculate, i.e. store them as is
{:n 6 :d 15}
The only time you calculate is at the end, when you want a result, or if you want to check for equal.

clojure: reductions: applying function n times, keeping intermediate results

Problem Statement
Given n, x, f:
I want output of the form:
[x, f(x), f(f(x)), f(f(f(x))), ..., f^{n-1}(x)]
Existing solution
This can be done via reductions
(reductions
(fn [state _] (f state))
state
(range n))
Question
Is there a primitive that provides a shorter solution?
What you want is clojure.core/iterate, which provides f -> x -> [x, f(x), f^2(x), f^3(x), ...] and clojure.core/take which provides a way to slice the first n elements off of a sequence. take is lazy, as is iterate so there are no guarantees about side-effects.

Clojure :: arity-overloaded functions calling each other

Examples of Clojure arity-overloading on functions like the following (taken from the cookbook):
(defn argcount
([] 0) ; Zero arguments
([x] 1) ; One argument
([ x & args] (inc (count args)))) ; List of arguments
... use a form that doesn't seem to allow the functions of lower arity to simply call the functions of higher arity with some default values (that's a common idiom in Java).
Is some other special form used for that ?
There's usually a good way to express the higher arity arguments in a way that doesn't need to refer to other arities using higher order functions and map / reduce. In this case it's pretty simple:
(defn argcount
([] 0)
([x] 1)
([x & args]
(reduce + 1 (map (constantly 1) args))))
Notice the general form of the expression is:
(reduce reducing-function arity-1-value (map mapping-function rest-of-args))
You can't do everything this way, but this works for a surprisingly large proportion of multi-argument functions. It also gains the advnatages of laziness using map, so you can do crazy things like pass ten million arguments to a function with little fear:
(apply argcount (take 10000000 (range)))
=> 10000000
Try that in most other languages and your stack will be toast :-)
mikera's answer is awesome; I'd just add an additional method.
When the a default value is needed for an overloaded function, a local can be used.
In the example division below, the local requires numbers and precision. The defined function overloads the precision with a default value.
(def overloaded-division
(let [divide-with-precision
(fn [divisor dividend precision]
(with-precision precision (/ (bigdec divisor) (bigdec dividend))))]
(fn
;lower-arity calls higher with a default precision.
([divisor dividend] (divide-with-precision divisor dividend 10))
;if precision is supplied it is used.
([divisor dividend precision] (divide-with-precision divisor dividend precision)))
)
)
When called at lower-arity, the default it applied:
user=> (overloaded-division 3 7)
0.4285714286M
user=> (overloaded-division 3 7 40)
0.4285714285714285714285714285714285714286M

Execute function until certain condition holds

I want to repeatedly apply some function to some state until a condition holds true.
Function f takes a state, modifies it and returns it. Apply f again to the returned state and so on.
I think this would work.
(first (filter pred (iterate f x)))
But it's a bit ugly. Plus memory consumption is not ideal since iterator would be forced to evaluate and keep intermediate states until the state on which pred holds true is returned, at which point intermediate states should be garbage collected.
I know you can write a simple recursive function:
(loop [f x p] (if (p x) x (recur f (f x) p))
But I'm looking for a core library function (or some combination of functions) that does the same thing with the same memory efficiency.
What you really want is take-while:
take-while
function
Usage: (take-while pred coll)
Returns a lazy sequence of successive items from coll while
(pred item) returns true. pred must be free of side-effects.
EDIT
A way to use higher order functions to achieve the result you want might be to wrap your function into something to be consumed by trampoline, namely a function that will either return the final result or another function which will execute the next step. Here's the code:
(defn iterable [f] ; wraps your function
(fn step [pred x] ; returns a new function which will accept the predicate
(let [y (f x)] ; calculate the current step result
(if (pred y) ; recursion stop condition
(fn [] (step pred y)) ; then: return a new fn for trampoline, operates on y
y)))) ; else: return a value to exit the trampoline
The iterative execution would go as follows:
(trampoline (iterable dec) pos? 10)
Not sure what you mean by iterator - you're using it as if it were iterate, and I just want to be sure that's what you mean. At any rate, your solution looks fine to me and not at all ugly. And memory is not an issue either: iterate is free to throw away intermediate results whenever it's convenient because you aren't keeping any references to them, just calling filter on it in a "streaming" way.
I think you should just make your loop a simple recursive function:
(defn do-until [f x p]
(if (p x) x (recur f (f x) p)))
(do-until inc 0 #(> % 10)) ; => 11
How about drop-while
(first (drop-while (comp not pred) (iterate f x))
I don't think there is a core function that does this exactly and efficiently. Hence I would do this with loop/recur as follows:
(loop [x initial-value]
(if (pred x) x (recur (f x))))
Loop/recur is very efficient since it requires no additional storage and is implemented as a simple loop in the JVM.
If you're going to do this a lot, then you can always encapsulate the pattern in a macro.
Sounds like you want the while macro.
http://richhickey.github.com/clojure/clojure.core-api.html#clojure.core/while
Usage: (while test & body)
Repeatedly executes body while test expression is true. Presumes
some side-effect will cause test to become false/nil. Returns nil
In a slightly different use case the for macro supports :when and :while options too.
http://richhickey.github.com/clojure/clojure.core-api.html#clojure.core/for
Usage: (for seq-exprs body-expr)
List comprehension. Takes a vector of one or more
binding-form/collection-expr pairs, each followed by zero or more
modifiers, and yields a lazy sequence of evaluations of expr.
Collections are iterated in a nested fashion, rightmost fastest,
and nested coll-exprs can refer to bindings created in prior
binding-forms. Supported modifiers are: :let [binding-form expr ...],
:while test, :when test.
(take 100 (for [x (range 100000000) y (range 1000000) :while (< y x)] [x y]))