Left Recursion Elimination, Star Enclosure - recursion

I have a grammar that has left recursion I tried removing them and I was able to remove two of them but for one of them I don't know what to do!
Here is the grammar:
R -> R "|" S
R -> S
S -> S.T
S -> T
T -> T*
T -> U
U -> (R)
U -> a
U -> "ε"
I removed the left recursion in rule 1 and 3 but I don't know what to do for rule #5 which is a star enclosure.
I'd be grateful if you help on this problem.

Related

Calculating the Trace of a Matrix; Syntactical Errors

I was tasked with writing OCAML code to calculate the Trace of a square matrix (the values inside the diagonal of a matrix). As a bonus, and for my own understanding, I'd also like to write code to produce a list of the trace of a square matrix.
I've created a tail recursive function utilizing the List.map feature which strips the first element of each row, and so on and so forth.
let trace m =
let rec helper m acc =
match m with
|[] -> acc
|(x::_) -> helper(List.map(fun(y::ys) -> ys)) (acc+x)
in helper m 0 ;;
Unfortunately I believe my syntax is off and I am unsure how to go about solving this. I think I have the right theory/idea in mind but poor implementation. Any help would be greatly appreciated
This is the error I get when I run the code:
This expression has type 'a list list -> 'a list list but an expression was expected of type 'b list
1:Warning 8: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
[]
As #glennsl says, you should do the work to ask a good question. You don't tell us anything about the error you see, for example. Generally you should copy/paste the error text into your question.
When I copy/paste your code I see an error for this fragment:
(List.map (fun (y :: ys) -> ys))
List.map takes two parameters: the first is a function, which you have. The second is a list to map over, which you don't have here. Since you don't supply a list, the value of this expression is a function that expects a list and returns the transformed list.
Since the first parameter of helper is a list of lists (I assume), and not a function, you have a type error. (Not a syntax error.)
Most likely you need to supply the list over which you want to map your function.

Two different types of OCaml recursive functions

During two weeks I've been doing some simple programs in OCaml. I've noticed that when we are working with a recursive structure T and we want to have the information I on T then depending on the information I we have two types of recursive function.
For simplicity let's assume T is a binary tree. So I'll use the following type :
type 'a tree = Empty | 'a * 'a tree * 'a tree
Now let's say the information I can be calculated from left to right on the binary tree. When I am saying left to right it means that the information I can be calculated from the root to the leaves without getting backward.
To be more clear let's say the information I we want to have is simply "the number of nodes of the binary tree". Then what's nice with this information is that when we get to all leaves then we get I, so we are going left to right in the sense that we begin from the root and expend recursively to the left and right subtree and the end case is when we arrived at the leaves.
So we simply have :
let rec nodes = function
|Empty -> 0 (*it's ok we are done here*)
|Node(_,l,r) -> 1 + nodes l + nodes r
What's very nice is that when the information can be calculated left to right then OCaml's pattern matching is a very strong tool and the information I can be calculated in an easy way.
So more generally we have :
let rec get_information = function
| Empty -> (*here we are done so we return a constant value*)
|Node(_,l,r)-> (*here we apply recusrively the function to the left and right tree*)
Now here comes my problem. Let's say I is an information that can't be calculated from left to right but from right to left. So it means that to get the information I we need to begin from the leaves of the tree and extend recursively to the top and we are done only when we get to the root of the binary tree (so the end case is when we get to the root of the binary tree and not the leaves).
For example, let's say the information I is : "the binary tree has the propriety that for every node the number of nodes in his left subtree is strictly superior to the number of nodes in his right subtree". If we want to solve this in linear time then we need to begin from the leaves and expend recursively to the top (note that I don't necessarily want a solution to the problem).
So to me, it's tricky to write a function that gets the information I when I is a right to left information (it needs to begin from the leaves and extend to the top). On the contrary pattern-matching is perfect when the information is a left to right information.
So my question is how to do when we need to write a function that gets the information I (when I is right to left)? Are there techniques to solve these kind of problems? Is it still possible to use pattern matching in a tricky way in order to get the desired result?
Pattern matching is useful for writing both kinds of function. Higher order functions called folds can also be used.
First, a concrete version. We will want to know whether a tree is left leaning, and if so, how many nodes it has. An int option will represent this nicely, with None indicating any non-left leaning tree.
type 'a tree = Empty | Branch of 'a * 'a tree * 'a tree
let rec tree_info = function
| Empty -> Some 0
| Branch (_, l, r) ->
match tree_info l, tree_info r with
| Some x, Some y when x >= y -> Some (x + y + 1)
| _ -> None
let is_left_leaning tree =
match tree_info tree with
| Some _ -> true
| None -> false
(Note that the condition x >= y is not 'strictly greater than', but this is deliberate; x > y is a poor choice. I'll leave figuring out why as an exercise.)
We can also express this style of function in terms of an operation called a right fold. For this operation one provides a value for each constructor of the datatype being folded over: in each place that constructor occurs, the fold operation will use that value to compute the result of the fold:
let rec foldr empty branch = function
| Empty -> empty
| Branch (x, l, r) ->
branch x (foldr empty branch l) (foldr empty branch r)
Note that the empty value and the Empty constructor have the same arity, and the branch value and the Branch constructor have the same arity, with corresponding argument types. That's characteristic of a right fold.
Given foldr, we can easily define map:
let map f tree =
foldr Empty (fun x l r -> Branch (f x, l, r)) tree
Or of course, 'tree_info':
let tree_info tree =
foldr
(Some 0)
(fun _ l r ->
match l, r with
| Some x, Some y when x >= y -> Some (x + y + 1)
| _ -> None)
tree
This is the alternative to pattern matching on the constructors of tree.

F# tree-building function causes stack overflow in Xamarin Studio

I'm trying to build up some rules in a tree structure, with logic gates i.e. and, not, or as well as conditions, e.g. property x equals value y. I wrote the most obvious recursive function first, which worked. I then tried to write a version that wouldn't cause a stack-overflow in continuation passing style taking my cue from this post about generic tree folding and this answer on stackoverflow.
It works for small trees (depth of approximately 1000), but unfortunately when using a large tree it causes a stackoverflow when I run it on my Mac with Xamarin Studio. Can anyone tell me whether I've misunderstood how F# treats tail-recursive code or whether this code isn't tail-recursive?
The full sample is here.
let FoldTree andF orF notF leafV t data =
let rec Loop t cont =
match t with
| AndGate (left, right)->
Loop left (fun lacc ->
Loop right (fun racc ->
cont (andF lacc racc)))
| OrGate (left, right)->
Loop left (fun lacc ->
Loop right (fun racc ->
cont (orF lacc racc)))
| NotGate exp ->
Loop exp (fun acc -> cont (notF acc))
| EqualsExpression(property,value) -> cont (leafV (property,value))
Loop t id
let evaluateContinuationPassingStyle tree data =
FoldTree (&&) (||) (not) (fun (prop,value) -> data |> Map.find prop |> ((=) value)) tree data
The code is tail-recursive, you got it right. But the problem is with Mono. See, Mono is not as high-quality implementation of .NET as the official thing. In particular, it doesn't do tail call elimination. Like, at all.
For the simplest (and most prevalent) case of self-recursion this doesn't matter too much, because the compiler catches it earlier. The F# compiler is smart enough to spot that the function is calling itself, figure out under what conditions, and convert it into a neat while loop, so that the compiled code doesn't make any calls at all.
But when your tail call is to a function passed as parameter, the compiler can't do that, because the actual function being called isn't known until runtime. In fact, even mutual recursion of two functions can't be converted into a loop reliably.
Possible solutions:
Switch to .NET Core.
Don't use recursive continuations, use accumulator instead (might not be possible).
Use self-recursion and pass manually maintained stack of continuations.
If all else fails, use a mutable stack.

Type Mismatch in ocaml

I am trying to recursively find the nth element in a list in ocaml using the following code.
let rec get_val x n = match x with
[] -> -1
| h::t -> if (n=0) then h else get_val t (n-1)
;;
print_int get_val [1; 2; 3] 1;;
However this code is giving me the error
This function has type int -> unit
It is applied to too many arguments; maybe you forgot a `;'.
Your definition is asking for two separate parameters (i.e., it is curried). But you're passing a pair of parameters (t, n - 1). These aren't the same thing.
To get past this problem, change the recursive call to get_val t (n - 1).
You might consider raising the Not_found exception when the list is too short. That way your code will work for lists of all types.
Update
Now the error is in the line where you test your function. You need parentheses there as well.
(You shouldn't keep changing your code. People who come to this page later won't be able to follow the questions and answers.)

What type of math is this: a -> b -> c

I often see type declarations similar to this when looking at Haskell:
a -> (b -> c)
I understand that it describes a function that takes in something of type a and returns a new function that takes in something of type b and returns something of type c. I also understand that types are associative (edit: I was wrong about this - see the comments below), so the above could be rewritten like this to get the same result:
(a -> b) -> c
This would describe a function that takes in something of type a and something of type b and returns something of type c.
I've also heard that you can make a complement (edit: really, the word I was looking for here is dual - see the comments below) to the function by switching the arrows:
a <- b <- c
which I think is equivalent to
c -> b -> a
but I'm not sure.
My question is, what is the name of this kind of math? I'd like to learn more about it so I can use it to help me write better programs. I'm interested in learning things like what a complimentary function is, and what other transformations can be performed on type declarations.
Thanks!
Type declarations are not associative, a -> (b -> c) is not equivalent to (a -> b) -> c. Also, you can't "switch" the arrows, a <- b <- c is not valid syntax.
The usual reference to associativity is in this case that -> it right associative, which means that a -> b -> c is interpreted as a -> (b -> c).
Speaking broadly this falls into the realm of Lambda Calculus.
Since this notation has to do with types of functions type inference might be of interest to you as well.
(The wrong assumptions you made about associativity should already be cleared up sufficiently by the other answers so i will not reiterate that)
a -> (b -> c)
and
(a -> b) -> c
are not equivalent in Haskell. That is type theory which can be founded in category theory.
The former is a function taking an argument of type a and returning a function of type b -> c. While the latter is a function taking a function of type a -> b as argument and returning a value of type c.
What do you mean by the complement of a function? The type of the inverse function of a function of type a -> (b -> c) has the type (b -> c) -> a.
Functions of type a->b->c, which are actually chains of functions like you said, are examples of Currying

Resources