Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Balanced Language, 2 Non-Terminal Symbols, List Comprehension

So, I was reading a book, "An Introduction to Formal Language Theory" and it describes a language L(G) = {a^n ++ b^n | n > 0}.

It has the following productions:

S -> ab | aSb

And so would produce the following language:

a, ab, aabb, aaabbb, ...

I was wondering how I could use Haskell's list comprehension to create this language. I know I can do list comprehension with strings, but I'm pretty much of a beginner and wasn't sure how I could get an infinite list like I would like of these strings.

I'm imagining something like:

[ x ++ y | x <- ["a","aa",..] y <- ["b","bb",..]] 
like image 343
user6189164 Avatar asked Sep 25 '17 18:09

user6189164


1 Answers

Working from the production rule,

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 could work with a small edit,

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

so that it uses Parallel List Comprehensions extension (:set -XParallelListComp in GHCi), except for the enumerations. But this is simple to fix,

[ x ++ y | x <- [replicate n 'a' | n <- [1..]] 
         | y <- [replicate n 'b' | n <- [1..]]]
like image 81
Will Ness Avatar answered Nov 17 '22 16:11

Will Ness