I am trying to write some code that recursively finds Taylor coefficients by taking derivatives of a function and then once at the base case evaluates the derivatives at x=0. Here's the code I have so far:
test(f, n) := block([df],
define(df(x), diff(f(x), x)),
print(n, "|", df(x), "|", f(x)),
if n = 0
then f(0)
else test(df, n-1)
);
test_func(x) := x^2;
test(test_func, 2);
The trouble is that this is what I get:
(%i4) test(test_func,2)
2
2 | 2 x | x
1 | 2 | 2
0 | 0 | 0
(%o4) 0
As you can see, the first time through everything looks good, f(x) is x^2, df(x) is 2x. However, the second time through f(x) is 2, even though df(x) was 2x the last time through the function. I'm somewhat new to Maxima so it's quite possible that I'm simply missing something obvious (i.e. don't assume I'm not making a stupid mistake).
My advice is to work with expressions instead of named functions. Something like this:
test(e, n) := block([e1 : diff(e, x)],
print(n, "|", e, "|", e1),
if n = 0
then ev(e, x = 0)
else test(e1, n - 1));
Related
Hi I'm trying to learn SML. I'm having trouble understanding the some of the recursive functions I'm coming across , for example
fun Square (x:int, y:int)=
if y=0
then 1
else x * Square(x,y-1);
I understand that in the else bracket the x is being multiplied by the value of the Square function taking x and y-1 as arguments and this process will continue until y hits 0 . I'm just not clear in each step of the recursion what is x being multiplied by? Furthermore once y hits 0 why doesn't the function return 1?
Thank you
The function does return 1 when y = 0, but this value is returned to the caller - Square(x,1) - which returns a value to its caller, Square(x,2), and so on.
(The big secret of recursive function is that they work exactly like non-recursive functions.)
I think one of the best ways towards understanding is to use the substitution method.
Look at Square (3,2). Replacing x and y in the function definition with their values gives
if 2 = 0 then 1 else 3 * Square (3, 2-1)
2 is clearly not 0, so we need to figure out what Square (3, 1) is before we can continue with the multiplication.
Repeat the same process:
if 1 = 0 then 1 else 3 * Square (3, 1-1)
The condition is still false, so continue with Square (3,0).
if 0 = 0 then 1 else 3 * Square (3, 0-1)
Now the condition is true, so we know that Square (3,0) is 1.
Move back one level and substitute:
if 1 = 0 then 1 else 3 * 1
So, Square (3,1) is 3. Substitute again:
if 2 = 0 then 1 else 3 * 3
which makes 9, which is what you would expect.
You could also consider this (endless) sequence of non-recursive functions:
...
fun Square_3 (x, y) = if y = 0 then 1 else x * Square_2 (x, y-1)
fun Square_2 (x, y) = if y = 0 then 1 else x * Square_1 (x, y-1)
fun Square_1 (x, y) = if y = 0 then 1 else x * Square_0 (x, y-1)
fun Square_0 (x, y) = if y = 0 then 1 else x * Square_minus1(x, y-1)
fun Square_minus1 (x, y) = ...
and then think about how Square_2(3, 2) works. Square(3,2) works in exactly the same way.
(By the way, your function has a pretty odd name. You might want to rename it.)
I am trying to build up subtraction, addition, division, multiplication and other operations using only following ones:
incr(x) - Once this function is called it will assign x + 1 to x
assign(x, y) - This function will assign the value of y to x (x = y)
zero(x) - This function will assign 0 to x (x = 0)
loop X { } - operations written within brackets will be executed X times
Using following rules it is straight forward to implement addition (add) like this:
ADD (x, y) {
loop X {
y = incr (y)
}
return y
}
However, I'm struggling to implement subtraction. I think that all the other needed operations could be completed using subtraction.
Any hint will be very appreciated.
Stephen Cole Kleene devised a way to perform integer subtraction using integer addition. However, it assumes that you cannot have negative integers. For example:
0 - 1 = 0
1 - 1 = 0
2 - 1 = 1
3 - 1 = 2
4 - 1 = 3
5 - 2 = 3
6 - 3 = 3
6 - 4 = 2
6 - 5 = 1
6 - 6 = 0
6 - 7 = 0
In your question, you implemented the addition operation using the increment operation.
Similarly, you can implement the subtraction operation using the decrement operation as follows:
sub(x, y) {
loop y
{ x = decr(x) }
return x
}
Now, all we need to do is implement the decrement operation.
This is where the genuis of Kleene shines:
decr(x) {
y = 0
z = 0
loop x {
y = z
z = incr(z)
}
return y
}
Here we've used all the four operations. This is how it works:
We have two base cases, y (the base case for 0) and z (the base case for 1):
y = 0 - 1 = 0
z = 1 - 1 = 0
Hence, we initialize them both to 0.
When x is 0 we run the loop 0 times (i.e. never) and then we simply return y = 0.
When x is 1 then we run the loop once, assign y = z and then simply return y = z = 0.
Notice that every time we run the loop y holds the result of the current iteration while z holds the result of the next iteration. This is the reason why we require two base cases. The decrement function is not a continuous function. It is a piecewise function:
decr(0) = 0
decr(n + 1) = n
Kleene realized this when he went to the dentist and the dentist extracted two of his teeth. He was frustrated while trying to solve this very problem and when the dentist extracted two of his teeth he realized that he required two base cases.
I'm teaching myself OCaml, and the main resources I'm using for practice are some problem sets Cornell has made available from their 3110 class. One of the problems is to write a function to reverse an int (i.e: 1234 -> 4321, -1234 -> -4321, 2 -> 2, -10 -> -1 etc).
I have a working solution, but I'm concerned that it isn't exactly idiomatic OCaml:
let rev_int (i : int) : int =
let rec power cnt value =
if value / 10 = 0 then cnt
else power (10 * cnt) (value/10) in
let rec aux pow temp value =
if value <> 0 then aux (pow/10) (temp + (value mod 10 * pow)) (value / 10)
else temp in
aux (power 1 i) 0 i
It works properly in all cases as far as I can tell, but it just seems seriously "un-OCaml" to me, particularly because I'm running through the length of the int twice with two inner-functions. So I'm just wondering whether there's a more "OCaml" way to do this.
I would say, that the following is idiomatic enough.
(* [rev x] returns such value [y] that its decimal representation
is a reverse of decimal representation of [x], e.g.,
[rev 12345 = 54321] *)
let rev n =
let rec loop acc n =
if n = 0 then acc
else loop (acc * 10 + n mod 10) (n / 10) in
loop 0 n
But as Jeffrey said in a comment, your solution is quite idiomatic, although not the nicest one.
Btw, my own style, would be to write like this:
let rev n =
let rec loop acc = function
| 0 -> acc
| n -> loop (acc * 10 + n mod 10) (n / 10) in
loop 0 n
As I prefer pattern matching to if/then/else. But this is a matter of mine personal taste.
I can propose you some way of doing it:
let decompose_int i =
let r = i / 10 in
i - (r * 10) , r
This function allows me to decompose the integer as if I had a list.
For instance 1234 is decomposed into 4 and 123.
Then we reverse it.
let rec rev_int i = match decompose_int i with
| x , 0 -> 10 , x
| h , t ->
let (m,r) = rev_int t in
(10 * m, h * m + r)
The idea here is to return 10, 100, 1000... and so on to know where to place the last digit.
What I wanted to do here is to treat them as I would treat lists, decompose_int being a List.hd and List.tl equivalent.
Okay, so I'm a beginner in Prolog so I'm sorry if I can't quite get my question across very clearly but this is where I'm struggling:
divide_by(X, D, I, R) :- (D > X), I is 0, R is X.
divide_by(X, D, I, R) :-
X >= D,
X_1 is X - D,
I_1 is I + 1,
divide_by(X_1, D, I_1, R),
R is X_1.
I'm trying to write a program that will accept two arguments (X and D) and return the Iterations (I) and Remainder (R) so that it can display the result of X / D when the user enters:
divide_by(8,3,I,R). for example.
When tracing the code I know that I is incorrect because the first increment makes it equal to 0 and so the count for that is wrong. But I don't know how to declare I is 0 without it resetting every time it recurses through the loop. (I don't want to declare I as 0 in the query)
I also realised that when it has finished recursing (when X < D) then I is going to be set to 0 because of the base case.
Would anyone be kind enough to show me how I can fix this?
You need to introduce an accumulator and use a helper predicate, something like this:
divide(_,0,_,_) :- !, fail . % X/0 is undefined and so can't be solved.
divide(0,_,0,0) :- !. % 0/X is always 0.
divide(X,Y,Q,R) :- % the ordinary case, simply invoke the
divrem(X,Y,0,Q,R) % helper with the accumulator seeded with 0
.
divrem(X,Y,Q,Q,X) :- % if X < Y, we're done.
X < Y . %
divrem(X,Y,T,Q,R) :- % otherwise...
X >= Y , % as long as X >= Y,
X1 is X - Y , % compute the next X
T1 is T + 1 , % increment the accumulator
divrem(X1,Y,T1,Q,R) % recurse down
. % Easy!
I'm doing some homework but I've been stuck for hours on something.
I'm sure it's really trivial but I still can't wrap my head around it after digging through the all documentation available.
Can anybody give me a hand?
Basically, the exercise in OCaml programming asks to define the function x^n with the exponentiation by squaring algorithm.
I've looked at the solution:
let rec exp x = function
0 -> 1
| n when n mod 2 = 0 -> let y = exp x (n/2) in y*y
| n when n mod 2 <> 0 -> let y = exp x ((n-1)/2) in y*y*x
;;
What I don't understand in particular is how the parameter n can be omitted from the fun statement and why should it be used as a variable for a match with x, which has no apparent link with the definition of exponentiation by squaring.
Here's how I would do it:
let rec exp x n = match n with
0 -> 1
| n when (n mod 2) = 1 -> (exp x ((n-1)/2)) * (exp x ((n-1)/2)) * x
| n when (n mod 2) = 0 -> (exp x (n/2)) * (exp x (n/2))
;;
Your version is syntaxically correct, yields a good answer, but is long to execute.
In your code, exp is called recursively twice, thus yielding twice as much computation, each call yielding itself twice as much computation, etc. down to n=0. In the solution, exp is called only once, the result is storred in the variable y, then y is squared.
Now, about the syntax,
let f n = match n with
| 0 -> 0
| foo -> foo-1
is equivalent to:
let f = function
| 0 -> 0
| foo -> foo-1
The line let rec exp x = function is the begging of a function that takes two arguments: x, and an unnammed argument used in the pattern matching. In the pattern matching, the line
| n when n mod 2 = 0 ->
names this argument n. Not that a different name could be used in each case of the pattern matching (even if that would be less clear):
| n when n mod 2 = 0 -> let y = exp x (n/2) in y*y
| p when p mod 2 <> 0 -> let y = exp x ((p-1)/2) in y*y*x
The keyword "function" is not a syntaxic sugar for
match x with
but for
fun x -> match x with
thus
let rec exp x = function
could be replaced by
let rec exp x = fun y -> match y with
which is of course equivalent with your solution
let rec exp x y = match y with
Note that i wrote "y" and not "n" to avoid confusion. The n variable introduced after the match is a new variable, which is only related to the function parameter because it match it. For instance, instead of
let y = x in ...
you could write :
match x with y -> ...
In this match expression, the "y" expression is the "pattern" matched. And like any pattern, it binds its variables (here y) with the value matched. (here the value of x) And like any pattern, the variables in the pattern are new variables, which may shadow previously defined variables. In your code :
let rec exp x n = match n with
0 -> 1
| n when (n mod 2) = 1 -> (exp x ((n-1)/2)) * (exp x ((n-1)/2)) * x
| n when (n mod 2) = 0 -> (exp x (n/2)) * (exp x (n/2))
;;
the variable n in the two cases shadow the parameter n. This isn't a problem, though, since the two variable with the same name have the same value.