Balanced language, 2 non-terminal characters, list comprehension

So, I read the book "Introduction to the theory of formal language" and describes the language L(G) = {a^n ++ b^n | n > 0} L(G) = {a^n ++ b^n | n > 0} .

He has the following works:

 S -> ab | aSb 

And so the following language will be created:

 a, ab, aabb, aaabbb, ... 

I was wondering how I can use Haskell list comprehension to create this language. I know that I can execute a list with strings, but I am pretty much a beginner and did not know how I can get an infinite list, as I would like from these strings.

I present something like:

 [ x ++ y | x <- ["a","aa",..] y <- ["b","bb",..]] 
+5
source share
1 answer

Work from the rules of production,

 S -> ab | aSb 

we could write

 s = ["ab"] ++ [ "a" ++ x ++ "b" | x <- s ] 

so that

 ~> take 5 s ["ab","aabb","aaabbb","aaaabbbb","aaaaabbbbb"] it :: [[Char]] 

Your attempt may work with a little change,

 [ x ++ y | x <- ["a","aa",..] | y <- ["b","bb",..]] 

to use the parallel list extension ( :set -XParallelListComp in GHCi), except for enumerations. But it’s easy to fix,

 [ x ++ y | x <- [replicate n 'a' | n <- [1..]] | y <- [replicate n 'b' | n <- [1..]]] 
+8
source

Source: https://habr.com/ru/post/1272104/


All Articles