Removed left recursion from grammar, but now the grammar allows invalid derivations - grammar

I'm trying to remove the left recursion from a grammar, however after following an algorithm to do so I now believe the grammar I've produced allows for the derivation of statements that aren't valid.
A part of the grammar is as follows:
A -> a A b A c A d
A -> e A
A -> f
A -> A + A
A -> A * A
So from my understanding, the bottom two productions are direct left recursion and the way to remove the left recursion is by introducing a new nonterminal A', however I then get this:
A -> a A b A c A d A'
A -> e A A'
A -> f A'
A' -> + A A'
A' -> * A A'
A' -> epsilon
Yet this allows the derivation of a A b A c A d * f
Which would not be a valid derivation with the original grammar. Can please someone please explain what I'm doing wrong?

Related

Query for all N elements in an M:N relation

Say I have the following tables that model tags attached to articles:
articles (article_id, title, created_at, content)
tags (tag_id, tagname)
articles_tags (article_fk, tag_fk)
What is the idiomatic way to retrieve the n newest articles with all their attached tag-names? This appears to be a standard problem, yet I am new to SQL and don't see how to elegantly solve this problem.
From an application perspective, I would like to write a function that returns a list of records of the form [title, content, [tags]], i.e., all the tags attache to an article would be contained in a variable length list. SQL relations aren't that flexible; so far, I can only think about a query to joint the tables that returns a new row for each article/tag combination, which I then need to programmatically condense into the above form.
Alternatively, I can think of a solution where I issue two queries: First, for the articles; second, an inner join on the link table and the tag table. Then, in the application, I can filter the result set for each article_id to obtain all tags for a given article? The latter seems to be a rather verbose and inefficient solution.
Am I missing something? Is there a canonical way to formulate a single query? Or a single query plus minor postprocessing?
On top of the bare SQL question, how would a corresponding query look like in the Opaleye DSL? That is, if it can be translated at all?
You would typically use a row-limiting query that selects the articles and orders them by descending date, and a join or a correlated subquery with an aggregation function to generate the list of tags.
The following query gives you the 10 most recent articles, along with the name of their related tags in an array:
select
a.*,
(
select array_agg(t.tagname)
from article_tags art
inner join tags t on t.tag_id = art.tag_fk
where art.article_fk = a.article_id
) tags
from articles
order by a.created_at desc
limit 10
You have converted most of GMB's answer successfully to Opaleye in your answer to your subsequent question. Here's a fully-working version in Opaleye.
In the future you are welcome to ask such questions on Opaleye's issue tracker. You will probably get a quicker response there.
{-# LANGUAGE Arrows #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TemplateHaskell #-}
import Control.Arrow
import qualified Opaleye as OE
import qualified Data.Profunctor as P
import Data.Profunctor.Product.TH (makeAdaptorAndInstance')
type F field = OE.Field field
data TaggedArticle a b c =
TaggedArticle { articleFk :: a, tagFk :: b, createdAt :: c}
type TaggedArticleR = TaggedArticle (F OE.SqlInt8) (F OE.SqlInt8) (F OE.SqlDate)
data Tag a b = Tag { tagKey :: a, tagName :: b }
type TagR = Tag (F OE.SqlInt8) (F OE.SqlText)
$(makeAdaptorAndInstance' ''TaggedArticle)
$(makeAdaptorAndInstance' ''Tag)
tagsTable :: OE.Table TagR TagR
tagsTable = error "Fill in the definition of tagsTable"
taggedArticlesTable :: OE.Table TaggedArticleR TaggedArticleR
taggedArticlesTable = error "Fill in the definition of taggedArticlesTable"
-- | Query all tags.
allTagsQ :: OE.Select TagR
allTagsQ = OE.selectTable tagsTable
-- | Query all article-tag relations.
allTaggedArticlesQ :: OE.Select TaggedArticleR
allTaggedArticlesQ = OE.selectTable taggedArticlesTable
-- | Join article-ids and tag names for all articles.
articleTagNamesQ :: OE.Select (F OE.SqlInt8, F OE.SqlText, F OE.SqlDate)
articleTagNamesQ = proc () -> do
ta <- allTaggedArticlesQ -< ()
t <- allTagsQ -< ()
OE.restrict -< tagFk ta OE..=== tagKey t -- INNER JOIN ON
returnA -< (articleFk ta, tagName t, createdAt ta)
-- | Aggregate all tag names for all articles
articleTagsQ :: OE.Select (F OE.SqlInt8, F (OE.SqlArray OE.SqlText))
articleTagsQ =
OE.aggregate ((,) <$> P.lmap (\(i, _, _) -> i) OE.groupBy
<*> P.lmap (\(_, t, _) -> t) OE.arrayAgg)
(OE.limit 10 (OE.orderBy (OE.desc (\(_, _, ca) -> ca)) articleTagNamesQ))

Can I define the general concept of x==y = p(x) == p(y) in Idris?

I want to define a type constructor which embodies the concept of using a type wrapper to define equality on a domain type t1 by projecting onto a domain type t2 with a function p.
The following specific example works, where t1 = ABC, t2 = Nat and p is the function abc_2_nat:
%default total
data ABC = A | B | C
abc_2_nat : ABC -> Nat
abc_2_nat A = 1
abc_2_nat B = 1
abc_2_nat C = 2
data Projected_abc : Type where
Project_abc : ABC -> Projected_abc
Projected_abc_equals : Projected_abc -> Projected_abc -> Bool
Projected_abc_equals (Project_abc x) (Project_abc y) = abc_2_nat x == abc_2_nat y
Eq Projected_abc where
(==) = Projected_abc_equals
But, when I attempt to generalize as follows:
data Projected : t1 -> t2 -> (p: t1 -> t2) -> Type
where Project : t1 -> Projected t1 t2 p
Projected_equals : Projected t1 t2 p -> Projected t1 t2 p -> Bool
Projected_equals (Project x) (Project y) = ?hole
I get this hole:
- + Main.hole [P]
`-- phTy : Type
t2 : phTy
p : Type -> phTy
t1 : Type
x : t1
y : t1
--------------------------
Main.hole : Bool
This doesn't work because it doesn't recognise that p is of type t1->t2 (which is what I want).
I suspect that I'm asking too much to supply the projection function as an argument to a type constructor, and somehow have the projection function available in the scope of the definition of a function whose parameters belong to the constructed type.
Is there any way I can get this to work?
It's can be done. You Projected generalization is not accurate enough. You should specify types of t1 and t2. Like this:
data Projected : (t1: Type) -> (t2: Type) -> (p: t1 -> t2) -> Type where
Project : t1 -> Projected t1 t2 p
Without this Idris compiler can't guess what kind of thing are t1 and t2 exactly. One more note: to compare values of type t1 by comparing projections to t2 domain, you should be sure that you can compare values of type t2. Thus general projection equality looks like this:
projected_equals : Eq t2 => Projected t1 t2 p -> Projected t1 t2 p -> Bool
projected_equals {p} (Project x) (Project y) = p x == p y
And you can write Eq instance for it!
Eq t2 => Eq (Projected t1 t2 p) where
(==) = projected_equals
And it also works. So if you define something like this:
data ABC = A | B | C
abc_2_nat : ABC -> Nat
abc_2_nat A = 1
abc_2_nat B = 1
abc_2_nat C = 2
You can use your abc_2_nat projection to implement corresponding projector:
abcNatProjector : ABC -> Projected ABC Nat Main.abc_2_nat
abcNatProjector abc = Project abc
I have to use Main.abc_2_nat to resolve ambiguilty because otherwise abc_2_nat can be any implicit type parameter. Idris has no power to guess what you want. Gladly, compiler helps me with this warning:
Eq.idr:13:37-46:WARNING: abc_2_nat is bound as an implicit
Did you mean to refer to Main.abc_2_nat?
And now you can check in REPL that it works!
λΠ> abcNatProjector A == abcNatProjector B
True : Bool
λΠ> abcNatProjector A == abcNatProjector C
False : Bool
Bonus addition:
If you mark abcNatProjector as implicit function, like this:
implicit
abcNatProjector : ABC -> Projected ABC Nat Main.abc_2_nat
abcNatProjector abc = Project abc
You can define some fancy operator
infixr 5 ==^
(==^) : Eq t2 => Projected t1 t2 p -> Projected t1 t2 p -> Bool
(==^) = projected_equals
And compare values of type ABC with it without using abcNatProjector explicitly.
λΠ> A ==^ B
True : Bool
λΠ> A ==^ C
False : Bool

How to query logicblox

I have an entity predicate eg. "Person" with related functional predicates storing attributes about the entity.
Eg.
Person(x), Person:id(x:s) -> string(s).
Person:dateOfBirth[a] = b -> Person(a), datetime(b).
Person:height[a] = b -> Person(a), decimal(b).
Person:eyeColor[a] = b -> Person(a), string(b).
Person:occupation[a] = b -> Person(a), string(b).
What I would like to do is in the terminal, do the equivalent of the SQL query:
SELECT id, dateOfBirth, eyeColor FROM Person
I am aware of the print command to get the details of a single functional predicate, but I would like to get a combination of them.
lb print /workspace 'Person:dateOfBirth'
You can use the "lb query" command to execute arbitrary logiql queries against your database. Effectively you create a temporary, anonymous, predicate with the results you want to see, and then a rule for populating that predicate using the logiql language. So in your case it would be something like:
lb query <workspace> '_(id, dob, eye) <-
Person(p),
Person:id(p:id),
Person:dateOfBirth[p] = dob,
Person:eyeColor[p] = eye.'
Try the query command with joins:
lb query /workspace '_(x, y, z) <- Person(p), Person:id(p:x), Person:dateOfBirth[p] = y, Person:eyeColor[p] = z.'

Combining two tuples into one in oracle db

Say I have a bunch of letters grouped together and I want to find out which pair bonds with another the most, as an example I have
a b d b
b c e a
and it should return ab or ba because a-b are the most occurred here.
so far I have made a query that just pulls every two letters that are together, but when I run the query I get something like the above example but all are in separate tuples, like this
a
b
b
c
d
e
b
a
I need to compare the occurence of all the PAIRS, my logic so far is that I can use nvl() to concat them(but nvl() of a-b and b-a returns two separate instances), then run a count, but I'm not sure how to run a count on these as I called the letters
select a.value, b.value
from Letter a, Letter b, Word aw, Word bw, Sentence senA, sentence senb
where a.id = aw.aid and aw.pid = sena.id and b.id = bw.aid and
bw.pid = senb.id and aw.pid = bw.pid and a.value != b.value
;
TL;DR: I want to do a count(a.ltr-b.ltr pair) but not sure how to code that.
Thanks!
EDIT: table structure:
letter(id, value)
\
word(aid, pid)
\
sentence(id, name,sid)
basically, if two letters end up in the same sentence.id, they are a pair(bond).

Constructing Language generated by the grammar

We have to find L(G), where grammar G is given as-
S->AB|CD, A->aA|a ,B->bB|bC, C->cD|d, D->aD|AD
I have attempted the question but it is recursing very deep and I am unable to terminate the string.[I know that A will generate a^n after n steps but what about D,C,B?]
Till now I have attempted as follows-
A->aA->aaA->....->a^(n-1)A (after n-1 steps)->a^n
B->bB->bbB->....->b^(m-1)B (after m-1 steps)->b^(m-1)bC->b^(m-1)bbC->...b^(m-1)b^(n-1)C->b^kC
C->cD->ccD->...->c^(p-1)D or c^(p-1)d[Thus we will consider as C->c^pD or C->c^pd]
D->aD->aaD->...->a^(q-1)D->a^(q-1)a^nD[Thus we will consider D->a^rD]
Now B depends on C and C depends on D and D depends on itself(i.e- D recurs on itself as D->a^rD)
So how can I find the grammar for this language which doesn't terminates?
D does not yield a string of terminals, so it is useless and can be omitted including all rules that has D.
The simplified grammar would be:
S->AB, A->aA|a ,B->bB|bC, C->d
And the language will be: {a^m b^n d : m,n>=1}