Grammar transformation for recursive descent - recursion

I am trying to transform a given grammar in order to be ready for recursive descent. The rules I end up are:
SEQ --> constSEQ | operZ
Z --> exprX | operX
Y --> exprX | operX
X --> expr | exproperX | ε .
What am I supposed to do with Z and Y that are the same?
Is any of them eliminated?

A bit hard to say without knowing the software system used (and its intelligence).
If on the left hand side all non-terminals must be unique (no or'ed rules Y --> exprX and Y --> operX), then the only purpose would be metainformation, maybe for a different semantic interpretation of a generated AST.
But yes, a fine possibility to loop reducing the grammar. On the other hand a produced function Y could just call Z.
(Mind exprX | operX might be the same as operX | exprX depending on the specific grammar's symbols or the type like LL(1).)
Also A --> X B and B -> X A are redundant.
One would need to loop over the rules till no reduction possible.
boolean checkRulesAreTheSame(Rule rule1, Rule rule2, Context context) {
context.setNonTerminalsTheSame(true, rule1.nonTerminal, rule2.nonTerminal);
if (productionsTheSame(rule1.production, rule2.production, context)) {
return true;
}
context.setNonTerminalsTheSame(false, rule1.nonTerminal, rule2.nonTerminal);
return false;
}
The rarer case A --> X B and B -> X C and C -> X A would not be found by this comparison of just 2 non-terminals.

Related

F# Strange difference in behavior of two recursive function definitions

I am trying to define a power function to compute x^y.
let rec powFunA (x,y) =
match (x,y) with
| (_,0) -> 1
| (x,y) -> x * powFunA (x,y-1);;
and
let rec powFunB x y =
match y with
| 0 -> 1
| y -> x * powFunB x y-1;;
The call powFunA (2,5) works and as expected gives me 32 as result. But somehow, I don't understand why, the second call powFunB 2 5 leads to a StackOverflowException.
I also came across a definition:
let rec power = function
| (_,0) -> 1.0 (* 1 *)
| (x,n) -> x * power(x,n-1) (* 2 *)
Can you please explain the absence of parameters and the usage of function on first line of definition.
Thanks.
This stack overflow error has to do with F#'s precedence rules. Consider this expression:
powFunB x y-1
This expression has some function application and the minus operator. In F# (as in all ML languages), function application has the highest precedence ever. Nothing can be more binding.
Therefore, the above expression is understood by the compiler as:
(powFunB x y) - 1
That is, function application powFunB x y first, minus operator second. Now, I hope, it's easy to see why this results in infinite recursion.
To fix, just apply parentheses to override precedence rules:
powFunB x (y-1)
The "parameterless" definition uses F# syntax for defining multicase functions. It's just a shortcut that allows to write = function instead of x = match x with. So, for example, the following two function are equivalent:
let f a = match a with | Some x -> [x] | None -> []
let g = function | Some x -> [x] | None -> []
Just some syntactic sugar, that's all. So the definition you found is exactly equivalent to your first snippet.

Regarding OCaml Pattern Matching Syntax

I am following this OCaml tutorial.
They provided the two functions below and said that they are equivalent.
let string_of_int x = match x with
| 0 -> "zero"
| 1 -> "one"
| 2 -> "two"
| _ -> "many"
let string_of_int2 = function
| 0 -> "zero"
| 1 -> "one"
| 2 -> "two"
| _ -> "many"
My query is regarding the syntax of the above functions.
I wrote the same function but instead of | 0 -> I simply did 0 -> and the function still works in the same way. Is there any particular reason that the tutorial added the extra | in their function?
In the second function what is the use of the function keyword and why was this keyword absent in the first function?
Some people think it looks nicer and more organized, and it allows you to change the order of cases using cut & paste without having to worry about which one didn't have the |.
The function syntax is an abbreviation: function [CASES] is the same as fun x -> match x with [CASES]. There is a subtle difference, which is with function it is not possible to shadow another variable by the name of the parameter.
let string_of_int x = [EXP] is itself an abbreviation for let string_of_int = fun x -> [EXP].
So, to a close approximation, the "canonical" syntax uses fun and match, everything else is sugar. If you apply these two expansions to the two versions of the function, you will see that the same code results (modulo alpha-equivalence, of course :) ).

Write a function with different return types in OCaml

How can I re-write this function in OCaml so that it allows the elements of the tuple to have different types
let nth i (x,y,z) =
match i with
1->x
|2->y
|3->z
|_->raise (Invalid_argument "nth")
The short answer is that it's not possible. OCaml is strongly and statically typed. A function returns a single type. Since your function returns x, y, and z in different cases, then these must all be the same type.
OCaml types are not like types in the so-called dynamically typed languages. You need to think differently. The benefits are (in my opinion) tremendous.
It can be done, but you need to fulfill the constraint that all values, returned from the function should be members of one type. The easiest solution is:
let nth i (x,y,z) =
match i with
| 1 -> `Fst x
| 2 -> `Snd y
| 3 -> `Thd z
| _ -> invalid_arg "nth tuple"
The solution demonstrates that you need to address all possible cases for the types of your tuple. Otherwise, your program will not be well-formed, and this contradicts with the static typing. The latter guarantees that your program is well-formed for any input, so that it wont fail in a runtime.
A twin solution, using ordinary ADT instead of polymorphic ones, will look something like this:
type ('a,'b,'c) t =
| Fst of 'a
| Snd of 'b
| Thd of 'c
let nth i (x,y,z) =
match i with
| 1 -> Fst x
| 2 -> Snd y
| 3 -> Thd z
| _ -> invalid_arg "nth tuple"
An exotic solution (not very practible, maybe) that uses GADT to form an existential type will look like this:
type t = Dyn : 'a -> t
let nth i (x,y,z) =
match i with
| 1 -> Dyn x
| 2 -> Dyn y
| 3 -> Dyn z
| _ -> invalid_arg "nth tuple"

Ocaml Pattern Matching Qualms

I'm having a bit of a problem with regards to pattern matching in Ocaml.
Basically, I need to write a function named reversed that accepts a list and checks whether or not it is in reversed order.
So far:
let rec reversed (x:int list):bool =
match x with
| [] -> true
| y::z::tl -> if y < z then false else reversed tl;
| y::[] -> true;;
It works! (to my surprise actually :P) But there is a flaw I can see, that is if there is no more tl, it would not match. Testing this returns true:
reversed [5;4;3;1;2];;
Which is perfectly understandable since there's no more tail and it simply matches to y::[]
How would I fix this?
PS: This is my first day with Ocaml. Sorry if the question is very easy :D
PPS: I am purposely only using Core. (no modules)
PPPS: I understand the case if I'm doing something fundamentally wrong, please do point it out.
The problem in your function is here :
| y::z::tl -> if y < z then false else reversed tl;
Let's look at your list : [5;4;3;1;2]
It is decomposed this way :
| 5::4::[3;1;2]
And you compare 5 and 4, and then call reverted with [3;2;1]. Wich means that the comparaison between 4 and 3 is not done ! (you can try with a list like [5;4;99;98;97], it is the unexpected result that you have).
What you should do is test on z, and then call reverted with the rest of the list. But if you try something like :
| y::z::_ -> if y < z then false else reversed z;
The compilers yells at you, because z is an int (and not an int list anymore). To solve this, you can "reconstruct" the list by adding z in front of tl :
| y::z::tl -> if y < z then false else reversed (z::tl)
Or name the list after y (which contains z) while still extracting z :
| y::(z::_ as tl) -> if y < z then false else reversed tl
As for your guess about the problem, I understand your logic but actually it does not work that way.
[] can be "named" in your decomposition, just as if it was a regular node.
Look at this example, a (bad) function who tests if the end of the list is reached :
let is_end l = match l with
| a -> false
| [] -> true;;
If you try to put that in your interpreter, you should get the following message :
Warning 11: this match case is unused.
That's because [] is already caught in the first match case. You can try with is_end [], it returns false.
The correct way to handle this is how you did it in your code :
let is_end l = match l with
| x::_ -> false
| [] -> true;;
Your program logic is wrong. You want to check if the list is reversed (decreasing?). But your program fails on input
[5;3;4;2;1]
telling you that it is reversed/decreasing. This is because you drop the 3 too early. Your middle clause should be:
| y::z::tl -> if y < z then false else reversed (z::tl);
You should use | y::z::tl -> if y < z then false else reversed (z::tl).
if y > z, you shouldn't drop z from the next round of list because z has not been compared to the next item yet.
Also you don't need ; in that line.
the correct code is
let rec reversed = function
| [] -> true
| hd::[] -> true
| hd1::hd2::tl ->
if hd1 < hd2 then false
else reversed (hd2::tl)
Here is another way to write it using some other concepts like pattern guards and wild cards:
let rec reversed = function
| [] | [_] -> true
| hd1::hd2::_ when hd1 < hd2 -> false
| _::tl -> reversed tl;;
This way there is one case for true, one for false, and one recursive.

map function if a predicate holds

I feel like this should be fairly obvious, or easy, but I just can't get it. What I want to do is apply a function to a list (using map) but only if a condition is held. Imagine you only wanted to divide the numbers which were even:
map (`div` 2) (even) [1,2,3,4]
And that would give out [1,1,3,2] since only the even numbers would have the function applied to them. Obviously this doesn't work, but is there a way to make this work without having to write a separate function that you can give to map? filter is almost there, except I also want to keep the elements which the condition doesn't hold for, and just not apply the function to them.
If you don't want to define separate function, then use lambda.
map (\x -> if (even x) then (x `div` 2) else x) [1,2,3,4]
Or instead of a map, list comprehension, bit more readable I think.
[if (even x) then (x `div` 2) else x | x <- [1,2,3,4]]
mapIf p f = map (\x -> if p x then f x else x)
In addition to the answer of PiotrLegnica: Often, it's easier to read if you declare a helper function instead of using a lambda. Consider this:
map helper [1..4] where
helper x | even x = x `div` 2
| otherwise = x
([1..4] is sugar for [1,2,3,4])
If you want to remove all the other elements instead, consider using filter. filter removes all elements that don't satisfy the predicate:
filter even [1..4] -> [2,4]
So you can build a pipe of mapand filter than or use list-comprehension instead:
map (`div` 2) $ filter even [1..4]
[x `div` 2 | x <- [1..4], even x]
Choose whatever you like best.
Make your own helper function maker:
ifP pred f x =
if pred x then f x
else x
custom_f = ifP even f
map custom_f [..]
(caveat: I don't have access to a compiler right now. I guess this works OK...)
I like the other, more general solutions, but in your very special case you can get away with
map (\x -> x `div` (2 - x `mod` 2)) [1..4]
Mostly a rip off of existing answers, but according to my biased definition of "readable" (I like guards more than ifs, and where more than let):
mapIf p f = map f'
where f' x | p x = f x | otherwise = x
ghci says it probably works
ghci> let mapIf p f = map f' where f' x | p x = f x | otherwise = x
ghci> mapIf even (+1) [1..10]
[1,3,3,5,5,7,7,9,9,11]

Resources