Size of propositional-logic formula in Standard ML - sml

I'm working on this problem, where the propositional logic formula is represented by:
datatype fmla =
F_Var of string
| F_Not of fmla
| F_And of fmla * fmla
| F_Or of fmla * fmla
Im trying to write a function that returns the size of a propositional-logic formula. A propositional variable has size 1; logical negation has size 1 plus the size of its sub-formula; logical conjunction and disjunction have size 1 plus the sizes of their sub-formulas.
How would I go about trying to solve this problem?

In general, when you have a sum type like this, it can be a good idea to start with a function definition that just lists each case but leaves out the implementation:
fun size (F_Var v) =
| size (F_Not f) =
| size (F_And (f1, f2)) =
| size (F_Or (f1, f2)) =
and then you fill in the definitions of the cases one at a time as you figure them out.
Since you already have a list of what the size is in each case;
A propositional variable has size 1.
A negation has size 1 plus the size of its sub-formula.
A conjunction has size 1 plus the sum of the sizes of its sub-formulas.
A disjunction has size 1 plus the sum of the sizes of its sub-formulas.
you can pretty much translate it directly into ML:
fun size (F_Var _) = 1
| size (F_Not f) = 1 + size f
| size (F_And (f1, f2)) = ...
| size (F_Or (f1, f2)) = ...
where I have left two cases for you to fill in.
Note that there is a very close correspondence between the definition in English and the definition in ML of each case.

Related

with C++ shortest path algorithm with two numbers. (c++)

if I got two integer a, b, I have to get the number of cases 2-D shortest path.
If a = 2, b = 3,
h- - -
| | | |
- - -
| | | |
- - -g
the path is from h to g.
Could you tell me how to get the number of cases with C++?
If you want the number of (shortest) paths, it would be
(a + b)! / (a! * b!)
! denote factorial
(permutation count with repetition).
(10 in your case as 5!/(2!*3!)).
std::next_permutation would be a good tool to iterate over them.

How does recursion get previous values?

I'm in the basic of the basic of learning c++, and ran into an example of recursion that I don't understand. The equation is for Fibonacci numbers, and is shown below:
int fibo(int f)
{
if (f < 3)
{
return 1;
}
else
{
return fibo(f - 2) + fibo(f - 1);
}
}
How does the "else" statement work? I know that it adds the two previous numbers to get the current fibbonacci number, but how does it know, without any prior information, where to start? If I want the 7th fibonacci number, how does it know what the 6th and 5th numbers are?
In this given equation, It will go deeper in the root. When you have given Value 7 initially, it will go to function itself to get value of 7-2 = 5 and 7-1=6, still its has not value of 5 and 6. so further it will decrease value of 5 to 3 and 4 and 6 to 5 and 4.
at the end when f is less then 3 it will return value 1. something like that after getting root values it will sum up those values to get total answer.
A recursive function will call itself as many times as it needs to compute the final value. For example, if you call fibo(3), it will call itself with fibo(2) and fibo(1).
You can understand it better if you write down a tree representing all the function calls (the numbers in brackets are the return values):
fibo(3) [1+1]
|
.--------------.
| |
fibo(2) [1] fibo(1) [1]
For fibo(7), you will have multple calls like so:
fibo(7) [fibo(6) + fibo(5)]
|
.-----------------------------------------------.
| |
fibo(6) [fibo(5) + fibo(4)] fibo(5) [fibo(4) + fibo(3)]
| |
.---------------------------------. ...
| |
fibo(5) [fibo(4) + fibo(3)] fibo(4) [fibo(3) + fibo(2)]
| |
... ...
Each recursive call will execute the same code, but with a different value of f. And each recursive call will have to call their own "editions" of the sub-cases (smaller values). This happens until everyone reaches the base case (f < 3).
I didn't draw the entire tree. But I guess you can see this grows very quick. There's a lot of repetition (fibo(7) calls fibo(6) and fibo(5), then fibo(6) calls fibo(5) again). This is why we usually don't implement Fibonacci recursively, except for studying recursion.

Writing power function in Standard ML with a predefined compound function

Having trouble writing a power function inStandard Ml. Im trying to write a function called exp of type int -> int -> int.
The application exp b e, for non-negative e, should return b^e.
For example, exp 3 2 should return 9. exp must be implemented with the function compound provided below. exp should not directly calls itself. Here is the compound function, it takes in a value n, a function, and a value x. All it does is it applies the function to the value x n number of times.
fun compound 0 f x = x
| compound n f x = compound (n-1) f (f x);
Im having trouble figuring out how to write this function without recursion, and with the restraint of having to use a function that only can use a function with one parameter. Anyone have any ideas of where to start with this?
This is what I have:
fun exp b 0 = 1
| exp b e = (compound e (fn x => x*x) b)
I know that this doesn't work, since if i put in 2^5 it will do:
2*2, 4*4, 16*16 etc.
You are extremely close. Your definition of exp compounds fn x => x*x which (as you noticed) is not what you want, because it is repeatedly squaring the input. Instead, you want to do repeated multiplication by the base. That is, fn x => b*x.
Next, you can actually remove the special case of e = 0 by relying upon the fact that compound "does the right thing" when asked to apply a function 0 times.
fun exp b e = compound e (fn x => b*x) 1
You could just do this instead I believe
fun exp 0 0 = 1
| exp b 0 = 1
| exp b e = (compound (e - 1) (fn x => b * x ) b);
this may not be exactly 100% proper code. I sort of just now read a bit of Standard ML documentation and took some code and reworked it for your example but the general idea is the same for most programming languages.
fun foo (num, power) =
let
val counter = ref power
val total = 1
in
while !counter > 0 do (
total := !total * num
counter := !counter - 1
)
end;
To be more clear with some pseudo-code:
input x, pow
total = 1
loop from 1 to pow
total = total * x
end loop
return total
This doesn't handle negative exponents but it should get you started.
It basically is a simple algorithm of what exponents truly are: repeated multiplication.
2^4 = 1*2*2*2*2 //The 1 is implicit
2^0 = 1

F# tricky recursive algorithm

I have this code in VBA (looping through the array a() of type double):
bm = 0 'tot
b = 0 'prev
For i = 24 To 0 Step -1
BP = b 'prevprev = prev
b = bm 'prev = tot
bm = T * b - BP + a(i) 'tot = a(i) + T * prev - prevprev
Next
p = Exp(-xa * xa) * (bm - BP) / 4 '* (tot - prevprev)/4
I'm putting this in F#. Clearly I could use an array and mutable variables to recreate the VBA. And maybe this is an example of the right time to use mutable that I've seen hinted at. But why not try to do it the most idiomatic way?
I could write a little recursive function to replicate the loop. But it kind of feels like littering to hang out a little sub-loop that has no meaning on its own as a standalone, named function.
I want to do it with List functions. I have a couple ideas, but I'm not there yet. Anyone get this in a snap??
The two vague ideas I have are: 1. I could make two more lists by chopping off one (and two) elements and adding zero-value element(s). And combine those lists. 2. I'm wondering if a list function like map can take trailing terms in the list as arguments. 3. As a general question, I wonder if this might be a case where an experienced person would say that this problem screams for mutable values (and if so does that dampen my enthusiasm for getting on the functional boat).
To give more intuition for the code: The full function that this is excerpted from is a numerical approximation for the cumulative normal distribution. I haven't looked up the math behind this one. "xa" is the absolute value of the main function argument "x" which is the number of standard deviations from zero. Without working through the proof, I don't think there's much more to say than: it's just a formula. (Oh and maybe I should change the variable names--xa and bm etc are pretty wretched. I did put suggestions as comments.)
It's just standard recursion. You make your exit condition and your recur condition.
let rec calc i prevPrev prev total =
if i = 0 then // exit condition; do your final calc
exp(-xa * xa) * (total - prevPrev) / 4.
else // recur condition, call again
let newPrevPrev = prev
let newPrev = total
let newTotal = (T * newPrev - newPrevPrev + a i)
calc (i-1) newPrevPrev newPrev newTotal
calc 24 initPrevPrev initPrev initTotal
or shorter...
let rec calc i prevPrev prev total =
if i = 0 then
exp(-xa * xa) * (total - prevPrev) / 4.
else
calc (i-1) prev total (T * total - prev + a i)
Here's my try at pulling the loop out as a recursive function. I'm not thrilled about the housekeeping to have this stand alone, but I think the syntax is neat. Aside from an error in the last line, that is, where the asterisk in (c * a.Tail.Head) gets the red squiggly for float list not matching type float (but I thought .Head necessarily returned float not list):
let rec RecurseIt (a: float list) c =
match a with
| []-> 0.0
| head::[]-> a.Head
| head::tail::[]-> a.Head + (c * a.Tail) + (RecurseIt a.Tail c)
| head::tail-> a.Head + (c * a.Tail.Head) - a.Tail.Tail.Head + (RecurseIt a.Tail c)
Now I'll try list functions. It seems like I'm going to have to iterate by element rather than finding a one-fell-swoop slick approach.
Also I note in this recursive function that all my recursive calls are in tail position I think--except for the last one which will come one line earlier. I wonder if this creates a stack overflow risk (ie, prevents the compiler from treating the recursion as a loop (if that's the right description), or if I'm still safe because the algo will run as a loop plus just one level of recursion).
EDIT:
Here's how I tried to return a list instead of the sum of the list (so that I could use the 3rd to last element and also sum the elements), but I'm way off with this syntax and still hacking away at it:
let rec RecurseIt (a: float list) c =
match a with
| []-> []
| head::[]-> [a.Head]
| head::tail::[]-> [a.Head + (c * a.Tail)] :: (RecurseIt a.Tail c)
| head::tail-> [a.Head + (c * a.Tail.Head) - a.Tail.Tail.Head] :: (RecurseIt a.Tail c)
Here's my try at a list function. I think the problem felt more complicated than it was due to confusing myself. I just had some nonsense with List.iteri here. Hopefully this is closer to making sense. I hoped some List. function would be neat. Didn't manage. For loop not so idiomatic I think. :
for i in 0 .. a.Length - 1 do
b::
a.Item(i) +
if i > 0 then
T * b.Item(i-1) -
if i > 1 then
b.Item(i-2)
else
0
else
0

looping for a series

I have this question:
Write a program to display the sum of the series 1+1/2+2/3+3/4+...
+(n-1)/n (using for loop).
I did not understand the series well, kindly explaint it for me if n = 6. (no need for coding).
For n = 6, you need to calculate 1 + (1/2) + (2/3) + (3/4) + (4/5) + (5/6)
The question is asking you to fill the details in to the following program:
sum = 0;
for (int i=1; i<=n; ++i) {
sum += ???
}
return sum;
where ??? should give you the following values:
i | ???
-------
1 | 1
2 | 1/2
3 | 2/3
4 | 3/4
5 | 4/5
6 | 5/6
.
.
.
n | (n-1)/n
It is simple. The biggest hint is the nth term itself : (n-1)/n
Except the first term, every other term can be represented by an expression of the form of (i-1)/i, which means the algorithm boils down to this:
double sum = 1.0; //first term
for(int i = 2 ; i <= n ; ++i) //2nd to nth term!
sum += (i-1.0)/i;
Why did I write (i-1.0) instead of (i-1)?
You need to figure that out yourself, as I already have explained and written almost the whole code.
Write a loop that evaluates (n-1)/n for each value of n and adds the outcome to some variable.
That "some variable" is the answer.
Set n=6
The final term of the series can also be written as n / (n + 1) where n is a value that iterates.