how to code this recursive grammar? - coding-style

I have the following grammar :
S -> S{S}S | null
Here null means nothing to be there in place of S.
I need to generate all possible strings of 2n brackets generated by this grammar.
I have tried to code it but the program runs out of memory. Could someone please help me code this grammar for 2n number of brackets?
Thanks a lot in advance

First, prove that this grammar generates all strings of balanced curly braces.
(Hint: Start by proving S -> S{S} | null generates all such strings.)
Then just write a function to generate all of those:
function generate(num_opens, num_closes, string_so_far, N)
if (num_opens + num_closes == N)
print string_so_far;
return;
if (num_opens > num_closes)
generate(num_opens, num_closes+1, string_so_far . '}', N)
generate(num_opens+1, num_closes, string_so_far . '{', N)
generate(0, 0, N)
This may or may not be in the "spirit" of the question.

Some psuedocode for you:
function grammar: S(string), n(int), generatedStrings(collection)
if (|S| == 2*n)
// Store in generatedStrings
return
else if (|S| > 2*n)
return
grammar(S + '{}', n, generatedStrings)
grammar(S +'{'+ S +'}', n, generatedStrings)
grammar(S +'{'+ S +'}'+ S, n, generatedStrings)
grammar('{'+ S +'}'+ S, n, generatedStrings)
grammar('{'+ S +'}', n, generatedStrings)
grammar('{}'+ S, n, generatedStrings)
Then you'll just need some mechanism to make sure you don't add duplicates to the set of generated strings. I'd use a set-type data structure (in other words, a structure that only allows one of each value to be stored) for that.

Related

Understanding this bubble sort solution in Prolog

How does this bubble sort solution work in Prolog?
bubblesort([], []).
bubblesort([H], [H]).
bubblesort([H|D], R) :-
bubblesort(D, E),
[B|G] = E,
( (H =< B, R = [H|E])
; (H > B, bubblesort([B,H|G], R))
).
Here is an example trace: https://pastebin.com/T0DLsmAV
I understand the the line bubblesort(D,E), is responsible for sorting it down to one element, but I don't understand how this works. I understand the basics of lists in prolog, but still cannot work out how this solution operates.
The main difficulty with this code is that bad variable names were chosen and are making the logic harder to follow than it needs to be.
The first two cases are obviously base cases. The first says "the empty list is already sorted" and the second says "a singleton list is already sorted." This should make sense. The third case is where things get interesting.
Let's examine the first part.
bubblesort([H|D], R) :-
bubblesort(D, E),
All that's happened so far is we've named our result R and broken our inputs into a first element H and a tail D. From there, we have said, let's bubblesort the tail of our input and call that E. Maybe this would be a little easier to follow?
bubblesort([H|T], Result) :-
bubblesort(T, TSorted),
Next up,
[B|G] = E,
Again, bad names, but what the author is intending to do here is straightforward: take apart the result of sorting the tail so we can talk about whether the next item in the sorted tail is the right element for that position, or if it needs to switch places with the head of our input. Let's rename:
[HeadOfTSorted|RestOfTSorted] = TSorted,
Now we have a condition. Think of it in terms of prepending onto a sorted list. Say you have some element, like 3, and I hand you a sorted list. You want to determine if your 3 goes at the front or somewhere else. Well, suppose I gave you a sorted list that looked like [5,7,19,23,...]. You'd know that your 3 is right where it needs to be, and you'd hand back [3,5,7,19,23,...]. That's exactly the first case of the condition:
( (H =< HeadOfTSorted, Result = [H|TSorted])
Now consider another case, where I hand you a list that starts with [1,2,...]. You know you can't just put the three at the start and give me back [3,1,2,...]. But you don't really know where the 3 goes; it just doesn't go at the start. So what you have to do is resort the rest of the list with the 3 at the start, after the 1: [1 | resorted([3,2,...])]. That's effectively the other branch of the condition:
; (H > HeadOfTSorted, bubblesort([HeadOfTSorted,H|RestOfTSorted], R))
).
Hope this helps!
note: the key to recursive problem solving is exactly not to think about the minutiae of our code's operations. Imagine you already have the solution, then just use it to solve a smaller subproblem, thus arriving at the full problem's solution.
Your code, with more suggestive variable names so I could follow it, reads:
bubblesort([], []). % empty list is already sorted
bubblesort([H], [H]). % singleton list is already sorted
bubblesort([H|T], S) :- % `[H|T]` sorted is `S`, *if*
bubblesort(T, [M|R]), % `T` sorted is `[M|R]`, *and*
( % *either*,
H =< M, % in case `H` is not greater than `M`,
S = [H,M|R] % `S` is `[H,M|R]`,
; % *or*
H > M, % in case `H` is greater than `M`,
bubblesort([M,H|R], S) % `S` is `[M,H|R]` sorted by the same algorithm
).
(H is for "head", T is for "tail", S is "sorted", R "rest" and M is "minimum" -- see below for that).
We prove its correctness by structural induction. The induction hypothesis (IH) is that this definition is correct for shorter lists. We need to prove it is then also correct for a longer list. Indeed T is one-element shorter than [H|T]. Thus IH says [M|R] is sorted. This means M is the minimum element in T. It also means T is non-empty (sorting doesn't change the number of elements), so the clauses are indeed mutually-exclusive.
If H is not larger than the minimum element in T, [H,M|R] is obviously sorted.
Otherwise, we sort [M,H|R]. M is the minimum element and thus guaranteed to be the first in the result. What's actually sorted is [H|R], which is one element shorter, thus by IH sorting it works. QED.
If the last step sounds fishy to you, consider replacing the second alternative with the equivalent
; H > M, % in case `H` is greater then `M`,
bubblesort([H|R], S1), % `S1` is `[H|R]` sorted by the same algorithm
S = [M|S1]
).
where the applicability of the induction step is even clearer.
I'm not so sure it's a bubble sort though.
update: Indeed, measuring the empirical orders of growth, its number of inferences grows as ~ n3 (or slower), but true bubble sort clocked at ~ n2.1 (close enough to the theoretical ~ n2), where n is the list's length:
tbs([], []). % 'true' bubble sort
tbs([H],[H]).
tbs(L,S):- bubble(L,B),
( L==B -> S=L ; tbs(B,S) ).
bubble([],[]).
bubble([A],[A]).
bubble([A,B|C],R):-
( A =< B -> bubble([B|C],X), R=[A|X]
; bubble([A|C],X), R=[B|X] ).

Turbo Prolog: 420 PROLOG.ERR missing

I'm quite new in Prolog. I'm trying to find the nth term and sum of a Fibonacci Series.
/* Fibonacci */
predicates
fibonacci(integer, integer, integer)
clauses
fibonacci(1,1,1):-!.
fibonacci(2,1,2):-!.
fibonacci(N, Term, Sum):-
N1 = N - 1,
N2 = N - 2,
fibonacci(N1, Term1, Sum1),
fibonacci(N2, Term2, Sum2),
Term = Term1 + Term2,
Sum = Term + Sum.
However while compiling in Turbo Prolog I'm getting 420 PROLOG.ERR missing on
fibonacci(N2, Term2, Sum2),
Why is this happening? Any help is appreciated. Thanks in advance.
Is that really the entire error message? It does not say what is missing?
EDIT: According to comments below, Turbo Prolog's = does indeed
correspond to is/2, so the remarks below, which are correct for
Prolog, don't apply. According to comments on the original question,
the terrible error message might be a singleton warning for Sum2.
In any case: Assuming that Turbo Prolog's clauses part corresponds to standard Prolog, none of N1, N2, Term and Sum will be integers in your program. = means unification, not arithmetic evaluation. If you call fibonacci(3, Term, Sum), then inside the call N1 will be bound to the uninterpreted term 3 - 1, not to the integer 2. The same goes for your other uses of =.
For the arithmetic part, you will want to use is/2: N1 is N - 1, N2 is N - 2 etc. This will evaluate the right-hand side as an arithmetic expression and actually bind these variables to integers.
Without thinking about it too hard, it's not clear to me if this will result in a useful computation for Term.
i guessing turbo cant find some file with error descriptions. looks like tp incorrectly installed? correct this and you get more informative message.
look at
http://rosettacode.org/mw/index.php?title=Fibonacci_sequence&action=edit&section=399
and modify it for not only finding Nth but Sum also.
you get something like:
----
% fibsum(i, n, fib(i-2), fib(i-1), fib(i), sum(i-1), sum(i))
fibsum(N, N, Fi2, Fi1, F, Si1, S) :-
F is Fi2 + Fi1,
S is Si1 + F.
fibsum(I, N, Fi2, Fi1, F, Si1, S) :-
In is I + 1,
Fn is Fi2 + Fi1,
Sn is Si1 + Fn, !,
fibsum(In, N, Fi1, Fn, F, Sn, S).
% fibs(i, fib(i), sum(i))
fibs(1, 1, 1).
fibs(2, 1, 2).
fibs(C, N, S) :-
C > 2,
fibsum(3, C, 1, 1, N, 2, S). % Generate from 3rd on
---
(barely tested on http://swish.swi-prolog.org/)
Turbo Prolog cannot find the error messages file PROLOG.ERR. That is normally installed in Turbo Prolog installation directory.
If the file is there, chek that the application path is correctly set under Setup->Directories->Turbo Directory

Evaluating three-variable expression in Prolog

Follow the Four-Step Abstract design process to define recursive rules to compute mathematical functions. You must indicate (use comments to code) which step is used. Note, a Prolog rule does not return a value. You need to use a parameter to hold the return value. You may NOT use the exponential operator ** to compute the expressions.
Write a recursive rules factbar(F, X, Y, N) to compute F = ((2*X + Y)^N)! (factorial of expbar). The rule must call (use) the rule expbar that you designed..
Now for doing this operation F = ((2*X + Y)^N) I have already written my code but I do not know how to write factorial in Prolog:
expbar(R, X, Y, N) :-
X > 0, Y > 0, N > 0,
R is (2 * X + Y) ** N.
Although I have used ** in my program for exponent I did not know how to use the other way.
I have no idea what the "four step abstract design process" is and you haven't included that detail. As a result, you're going to instead get my two-step recursive function design process. Your predicate is right except you haven't defined pow/3, a function to compute powers. This is obviously the crux of your assignment. Let's do it.
Step one: identify your base cases. With arithmetic functions, the base case involves the arithmetic identity. For exponentiation, the identity is 1. In other words, X**1 = X. Write this down:
pow(X,1,X).
Because this is a function with two inputs and one result, we'll encode it as an arity-3 predicate. This fact simply says X to the 1st power is X.
Step two. Now consider the inductive case. If I have X**N, I can expand it to X * (X**(N-1)). By the definition of exponentiation and the induction rule, this completes the definition of the predicate. Encode it in Prolog syntax:
pow(X,N,Y) :-
N > 1,
succ(N0, N),
pow(X, N0, Y0),
Y is X * Y0, !.
This gives you a predicate for calculating exponents. If you replace your use of **/2 in your expbar/4 predicate, you fulfill the requirements of your assignment.

What's the formal term for a function that can be written in terms of `fold`?

I use the LINQ Aggregate operator quite often. Essentially, it lets you "accumulate" a function over a sequence by repeatedly applying the function on the last computed value of the function and the next element of the sequence.
For example:
int[] numbers = ...
int result = numbers.Aggregate(0, (result, next) => result + next * next);
will compute the sum of the squares of the elements of an array.
After some googling, I discovered that the general term for this in functional programming is "fold". This got me curious about functions that could be written as folds. In other words, the f in f = fold op.
I think that a function that can be computed with this operator only needs to satisfy (please correct me if I am wrong):
f(x1, x2, ..., xn) = f(f(x1, x2, ..., xn-1), xn)
This property seems common enough to deserve a special name. Is there one?
An Iterated binary operation may be what you are looking for.
You would also need to add some stopping conditions like
f(x) = something
f(x1,x2) = something2
They define a binary operation f and another function F in the link I provided to handle what happens when you get down to f(x1,x2).
To clarify the question: 'sum of squares' is a special function because it has the property that it can be expressed in terms of the fold functional plus a lambda, ie
sumSq = fold ((result, next) => result + next * next) 0
Which functions f have this property, where dom f = { A tuples }, ran f :: B?
Clearly, due to the mechanics of fold, the statement that f is foldable is the assertion that there exists an h :: A * B -> B such that for any n > 0, x1, ..., xn in A, f ((x1,...xn)) = h (xn, f ((x1,...,xn-1))).
The assertion that the h exists says almost the same thing as your condition that
f((x1, x2, ..., xn)) = f((f((x1, x2, ..., xn-1)), xn)) (*)
so you were very nearly correct; the difference is that you are requiring A=B which is a bit more restrictive than being a general fold-expressible function. More problematically though, fold in general also takes a starting value a, which is set to a = f nil. The main reason your formulation (*) is wrong is that it assumes that h is whatever f does on pair lists, but that is only true when h(x, a) = a. That is, in your example of sum of squares, the starting value you gave to Accumulate was 0, which is a does-nothing when you add it, but there are fold-expressible functions where the starting value does something, in which case we have a fold-expressible function which does not satisfy (*).
For example, take this fold-expressible function lengthPlusOne:
lengthPlusOne = fold ((result, next) => result + 1) 1
f (1) = 2, but f(f(), 1) = f(1, 1) = 3.
Finally, let's give an example of a functions on lists not expressible in terms of fold. Suppose we had a black box function and tested it on these inputs:
f (1) = 1
f (1, 1) = 1 (1)
f (2, 1) = 1
f (1, 2, 1) = 2 (2)
Such a function on tuples (=finite lists) obviously exists (we can just define it to have those outputs above and be zero on any other lists). Yet, it is not foldable because (1) implies h(1,1)=1, while (2) implies h(1,1)=2.
I don't know if there is other terminology than just saying 'a function expressible as a fold'. Perhaps a (left/right) context-free list function would be a good way of describing it?
In functional programming, fold is used to aggregate results on collections like list, array, sequence... Your formulation of fold is incorrect, which leads to confusion. A correct formulation could be:
fold f e [x1, x2, x3,..., xn] = f((...f(f(f(e, x1),x2),x3)...), xn)
The requirement for f is actually very loose. Lets say the type of elements is T and type of e is U. So function f indeed takes two arguments, the first one of type U and the second one of type T, and returns a value of type U (because this value will be supplied as the first argument of function f again). In short, we have an "accumulate" function with a signature f: U * T -> U. Due to this reason, I don't think there is a formal term for these kinds of function.
In your example, e = 0, T = int, U = int and your lambda function (result, next) => result + next * next has a signaturef: int * int -> int, which satisfies the condition of "foldable" functions.
In case you want to know, another variant of fold is foldBack, which accumulates results with the reverse order from xn to x1:
foldBack f [x1, x2,..., xn] e = f(x1,f(x2,...,f(n,e)...))
There are interesting cases with commutative functions, which satisfy f(x, y) = f(x, y), when fold and foldBack return the same result. About fold itself, it is a specific instance of catamorphism in category theory. You can read more about catamorphism here.

mathematica FullSimplify cowardly refusing fully evaluate real parts of a complex number?

I'm wondering if there is a different command than FullSimplify to tell mathematica to do the computation requested. Here's three variations of a simplification attempt
FullSimplify[Re[ (-I + k Rr)] Cos[Ttheta], Element[{k, Rr, Ttheta, t, omega}, Reals]]
FullSimplify[Re[E^(I (omega t - k Rr)) ] Cos[Ttheta], Element[{k, Rr, Ttheta, t, omega}, Reals]]
FullSimplify[Re[E^(I (omega t - k Rr)) (-I + k Rr)] Cos[Ttheta], Element[{k, Rr, Ttheta, t, omega}, Reals]]
I get respectively:
k Rr Cos[Ttheta]
Cos[k Rr - omega t] Cos[Ttheta]
I (-k Rr + omega t)
Cos[Ttheta] Re[E (-I + k Rr)]
Without the exponential, the real parts get evaluated. Without the complex factor multiplying the exponential, the real parts get evaluated. With both multiplied, the input is returned as output?
I tried the // Timings modifier, and this isn't because the expression is too complex (which is good since I can do this one in my head, but this was a subset of a larger test expression that was also failing).
Since your variables are declared Reals have you tried ComplexExpand?
To redeem my slow posting here is another approach: tell Mathematica that you do not want Complex in the result via ComplexityFunction
FullSimplify[Re[E^(I (omega t - k Rr)) (-I + k Rr)] Cos[Ttheta],
Element[{k, Rr, Ttheta, t, omega}, Reals],
ComplexityFunction -> (1 - Boole#FreeQ[#, Complex] &)]
ComplexExpand, perhaps?
ComplexExpand[Re[E^(I (omega t - k Rr)) (-I + k Rr)] Cos[Ttheta]]
This Is a problem I've been having with Mathematica for a long time, combining suggestions from here I've created a new function that can be used instead of Simplify[] when dealing with complex arguments. Works for me so far, any further suggestions?
CSimplify[in_] :=
FullSimplify[in // ComplexExpand,
ComplexityFunction -> (1 - Boole#FreeQ[#, Complex] &)]

Resources