<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ finite state machine - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ finite state machine - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 27 Jul 2026 22:42:50 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/finite-state-machine/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ What are Context Free Grammars? ]]>
                </title>
                <description>
                    <![CDATA[ By Aditya Have you ever noticed that, when you are writing code in a text editor like VS code, it recognizes things like unmatched braces? And it also sometimes warns you, with an irritating red highlight, about the incorrect syntax that you have wri... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/context-free-grammar/</link>
                <guid isPermaLink="false">66d45dd951f567b42d9f843b</guid>
                
                    <category>
                        <![CDATA[ compilers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ finite state machine ]]>
                    </category>
                
                    <category>
                        <![CDATA[ linguistics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programming languages ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 14 Jan 2020 09:39:14 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/01/Lee---Company.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Aditya</p>
<p>Have you ever noticed that, when you are writing code in a text editor like VS code, it recognizes things like unmatched braces? And it also sometimes warns you, with an irritating red highlight, about the incorrect syntax that you have written? </p>
<p>If not, then think about it. That is after all a piece of code. How can you write code for such a task? What would be the underlying logic behind it? </p>
<p>These are the kinds of questions that you will face if you have to write a compiler for a programming language. Writing a compiler is not an easy task. It is bulky job that demands a significant amount of time and effort. </p>
<p>In this article, we are not going to talk about how to build compilers. But we will talk about a concept that is a core component of the compiler: Context Free Grammars.</p>
<h2 id="heading-introduction">Introduction</h2>
<p>All the questions we asked earlier represent a problem that is significant to compiler design called Syntax Analysis. As the name suggests, the challenge is to analyze the syntax and see if it is correct or not. This is where we use Context Free Grammars. A Context Free Grammar is a set of rules that define a language. </p>
<p>Here, I would like to draw a distinction between Context Free Grammars and grammars for natural languages like English. </p>
<p>Context Free Grammars or CFGs define a formal language. Formal languages work strictly under the defined rules and their sentences are not influenced by the context. And that's where it gets the name <em>context free</em>. </p>
<p>Languages such as English fall under the category of Informal Languages since they are affected by context. They have many other features which a CFG cannot describe.</p>
<p>Even though CFGs cannot describe the context in the natural languages, they can still define the syntax and structure of sentences in these languages. In fact, that is the reason why the CFGs were introduced in the first place. </p>
<p>In this article we will attempt to generate English sentences using CFGs. We will learn how to describe the sentence structure and write rules for it. To do this, we will use a JavaScript library called Tracery which will generate sentences on the basis of rules we defined for our grammar.</p>
<p>Before we dive into the code and start writing the rules for the grammar, let's just discuss some basic terms that we will use in our CFG.</p>
<p><strong>Terminals</strong>: These are the characters that make up the actual content of the final sentence. These can include words or letters depending on which of these is used as the basic building block of a sentence.</p>
<p>In our case we will use words as the basic building blocks of our sentences. So our terminals will include words such as "to", "from", "the", "car", "spaceship", "kittens" and so on.</p>
<p><strong>Non Terminals</strong>: These are also called variables. These act as a sub language within the language defined by the grammar. Non terminals are placeholders for the terminals. We can use non terminals to generate different patterns of terminal symbols.</p>
<p>In our case we will use these Non terminals to generate noun phrases, verb phrases, different nouns, adjectives, verbs and so on.</p>
<p><strong>Start Symbol</strong>: a start symbol is a special non terminal that represents the initial string that will be generated by the grammar.</p>
<p>Now that we know the terminology let's start learning about the grammatical rules. </p>
<p>While writing grammar rules, we will start by defining the set of terminals and a start state. As we learned before, that start symbol is a non-terminal. This means it will belong to the set of non-terminals. </p>
<pre><code>T: (<span class="hljs-string">"Monkey"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"ate"</span>, <span class="hljs-string">"the"</span>)
<span class="hljs-attr">S</span>: Start state.
</code></pre><p>And the rules are:</p>
<pre><code>S --&gt; nounPhrase verbPhrase
nounPhrase --&gt; adj nounPhrase | adj noun
verbPhrase --&gt; verb nounPhrase
adjective  --&gt; the
noun --&gt; Monkey | banana
verb --&gt; ate
</code></pre><p>The above grammatical rules may seem somewhat cryptic at first. But if we look carefully, we can see a pattern that is being generated out of these rules. </p>
<p>A better way to think about the above rules is to visualise them in the form of a tree structure. In that tree we can put <em>S</em> in the root and <em>nounPhrase</em> and <em>verbPhrase</em> can be added as children of the root. We can proceed in the same way with <em>nounPhrase</em> and <em>verbPhrase</em> too. The tree will have terminals as its leaf nodes because that is where we end these derivations. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/parsetree.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the above image we can see that <em>S</em> (a nonterminal)  derives two non terminals <em>NP</em>(<em>nounPhrase</em>) and <em>VP</em>(<em>verbPhrase</em>). In the case of <em>NP</em>, it has derived two non terminals, <em>Adj</em> and <em>Noun</em>. </p>
<p>If you look at the grammar, <em>NP</em> could also have chosen <em>Adj</em> and <em>nounPhrase</em>. While generating text, these choices are made randomly. </p>
<p>And finally the leaf nodes have terminals which are written in the bold text. So if you move from left to right, you can see that a sentence is formed.</p>
<p>The term often used for this tree is a Parse Tree. We can create another parse tree for a different sentence generated by this grammar in a similar way. </p>
<p>Now let's proceed further to the code. As I mentioned earlier, we will use a JavaScript library called Tracery for text generation using CFGs. We will also write some code in HTML and CSS for the front-end part.</p>
<h2 id="heading-the-code">The Code</h2>
<p>Let's start by first getting the tracery library. You can clone the library from GitHub <a target="_blank" href="https://github.com/galaxykate/tracery">here</a>. I have also left the link to the GitHub repository by galaxykate at the end of the article.</p>
<p>Before we use the library we will have to import it. We can do this simply in an HTML file like this. </p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"tracery-master/js/vendor/jquery-1.11.2.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"tracery-master/tracery.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"tracery-master/js/grammars.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">'app.js'</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>I have added the cloned tracery file as a script in my HTML code. We will also have to add JQuery to our code because tracery depends on JQuery. Finally, I have added <em>app.js</em> which is the file where I will add rules for the grammar.</p>
<p>Once that is done, create a JavaScript file where we will define our grammar rules.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> rules = {
        <span class="hljs-string">"start"</span>: [<span class="hljs-string">"#NP# #VP#."</span>],
        <span class="hljs-string">"NP"</span>: [<span class="hljs-string">"#Det# #N#"</span>, <span class="hljs-string">"#Det# #N# that #VP#"</span>, <span class="hljs-string">"#Det# #Adj# #N#"</span>],
        <span class="hljs-string">"VP"</span>: [<span class="hljs-string">"#Vtrans# #NP#"</span>, <span class="hljs-string">"#Vintr#"</span>],
        <span class="hljs-string">"Det"</span>: [<span class="hljs-string">"The"</span>, <span class="hljs-string">"This"</span>, <span class="hljs-string">"That"</span>],
        <span class="hljs-string">"N"</span>: [<span class="hljs-string">"John Keating"</span>, <span class="hljs-string">"Bob Harris"</span>, <span class="hljs-string">"Bruce Wayne"</span>, <span class="hljs-string">"John Constantine"</span>, <span class="hljs-string">"Tony Stark"</span>, <span class="hljs-string">"John Wick"</span>, <span class="hljs-string">"Sherlock Holmes"</span>, <span class="hljs-string">"King Leonidas"</span>],
        <span class="hljs-string">"Adj"</span>: [<span class="hljs-string">"cool"</span>, <span class="hljs-string">"lazy"</span>, <span class="hljs-string">"amazed"</span>, <span class="hljs-string">"sweet"</span>],
        <span class="hljs-string">"Vtrans"</span>: [<span class="hljs-string">"computes"</span>, <span class="hljs-string">"examines"</span>, <span class="hljs-string">"helps"</span>, <span class="hljs-string">"prefers"</span>, <span class="hljs-string">"sends"</span>, <span class="hljs-string">"plays with"</span>, <span class="hljs-string">"messes up with"</span>],
        <span class="hljs-string">"Vintr"</span>: [<span class="hljs-string">"coughs"</span>, <span class="hljs-string">"daydreams"</span>, <span class="hljs-string">"whines"</span>, <span class="hljs-string">"slobbers"</span>, <span class="hljs-string">"appears"</span>, <span class="hljs-string">"disappears"</span>, <span class="hljs-string">"exists"</span>, <span class="hljs-string">"cries"</span>, <span class="hljs-string">"laughs"</span>]
    }
</code></pre>
<p>Here you will notice that the syntax for defining rules is not much different from how we defined our grammar earlier. There are very minor differences such as the way non-terminals are defined between the hash symbols. And also the way in which different derivations are written. Instead of using the "|" symbol for separating them, here we will put all the different derivations as different elements of an array. Other than that, we will use the semicolons instead of arrows to represent the transition. </p>
<p>This new grammar is a little more complicated than the one we defined earlier. This one includes many other things such as Determiners, Transitive Verbs and Intransitive Verbs. We do this to make the generated text look more natural. </p>
<p>Let's now call the tracery function "createGrammar" to create the grammar we just defined. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> grammar = tracery.createGrammar(rules);
</code></pre>
<p>This function will take the rules object and generate a grammar on the basis of these rules. After creating the grammar, we now want to generate some end result from it. To do that we will use a function called "flatten".</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> expansion = grammar.flatten(<span class="hljs-string">'#start#'</span>);
</code></pre>
<p>It will generate a random sentence based on the rules that we defined earlier. But let's not stop there. Let's also build a user interface for it. There's not much we will have to do for that part – we just need a button and some basic styles for the interface.</p>
<p>In the same HTML file where we added the libraries we will add some elements.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Weird Sentences<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span>/&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://fonts.googleapis.com/css?family=UnifrakturMaguntia&amp;display=swap"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://fonts.googleapis.com/css?family=Harmattan&amp;display=swap"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"tracery-master/js/vendor/jquery-1.11.2.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"tracery-master/tracery.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"tracery-master/js/grammars.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">'app.js'</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"h1"</span>&gt;</span>Weird Sentences<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"generate"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"generate()"</span>&gt;</span>Give me a Sentence!<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"sentences"</span>&gt;</span>

        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>And finally we will add some styles to it.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
    <span class="hljs-attribute">text-align</span>: center;
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'Harmattan'</span>, sans-serif;
}

<span class="hljs-selector-id">#h1</span> {
    <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'UnifrakturMaguntia'</span>, cursive;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">4em</span>;
    <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">37</span>, <span class="hljs-number">146</span>, <span class="hljs-number">235</span>);
    <span class="hljs-attribute">color</span>: white;
    <span class="hljs-attribute">padding</span>: .<span class="hljs-number">5em</span>;
    <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">1px</span> <span class="hljs-number">1px</span> <span class="hljs-number">1px</span> <span class="hljs-number">1px</span> <span class="hljs-built_in">rgb</span>(<span class="hljs-number">206</span>, <span class="hljs-number">204</span>, <span class="hljs-number">204</span>);
}

<span class="hljs-selector-id">#generate</span> {
    <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'Harmattan'</span>, sans-serif;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">2em</span>;
    <span class="hljs-attribute">font-weight</span>: bold;
    <span class="hljs-attribute">padding</span>: .<span class="hljs-number">5em</span>;
    <span class="hljs-attribute">margin</span>: .<span class="hljs-number">5em</span>;
    <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">1px</span> <span class="hljs-number">1px</span> <span class="hljs-number">1px</span> <span class="hljs-number">1px</span> <span class="hljs-built_in">rgb</span>(<span class="hljs-number">206</span>, <span class="hljs-number">204</span>, <span class="hljs-number">204</span>);
    <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">255</span>, <span class="hljs-number">0</span>, <span class="hljs-number">64</span>);
    <span class="hljs-attribute">color</span>: white;
    <span class="hljs-attribute">border</span>: none;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">2px</span>;
    <span class="hljs-attribute">outline</span>: none;
}

<span class="hljs-selector-id">#sentences</span> <span class="hljs-selector-tag">p</span> {
    <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">1px</span> <span class="hljs-number">1px</span> <span class="hljs-number">1px</span> <span class="hljs-number">1px</span> <span class="hljs-built_in">rgb</span>(<span class="hljs-number">206</span>, <span class="hljs-number">204</span>, <span class="hljs-number">204</span>);
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">2em</span>;
    <span class="hljs-attribute">margin-left</span>: <span class="hljs-number">15em</span>;
    <span class="hljs-attribute">margin-right</span>: <span class="hljs-number">15em</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">2em</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">2px</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1.5em</span>;
}
</code></pre>
<p>We will also have to add some more JavaScript to manipulate the interface.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> sentences = []
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">generate</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> data = {
        <span class="hljs-string">"start"</span>: [<span class="hljs-string">"#NP# #VP#."</span>],
        <span class="hljs-string">"NP"</span>: [<span class="hljs-string">"#Det# #N#"</span>, <span class="hljs-string">"#Det# #N# that #VP#"</span>, <span class="hljs-string">"#Det# #Adj# #N#"</span>],
        <span class="hljs-string">"VP"</span>: [<span class="hljs-string">"#Vtrans# #NP#"</span>, <span class="hljs-string">"#Vintr#"</span>],
        <span class="hljs-string">"Det"</span>: [<span class="hljs-string">"The"</span>, <span class="hljs-string">"This"</span>, <span class="hljs-string">"That"</span>],
        <span class="hljs-string">"N"</span>: [<span class="hljs-string">"John Keating"</span>, <span class="hljs-string">"Bob Harris"</span>, <span class="hljs-string">"Bruce Wayne"</span>, <span class="hljs-string">"John Constantine"</span>, <span class="hljs-string">"Tony Stark"</span>, <span class="hljs-string">"John Wick"</span>, <span class="hljs-string">"Sherlock Holmes"</span>, <span class="hljs-string">"King Leonidas"</span>],
        <span class="hljs-string">"Adj"</span>: [<span class="hljs-string">"cool"</span>, <span class="hljs-string">"lazy"</span>, <span class="hljs-string">"amazed"</span>, <span class="hljs-string">"sweet"</span>],
        <span class="hljs-string">"Vtrans"</span>: [<span class="hljs-string">"computes"</span>, <span class="hljs-string">"examines"</span>, <span class="hljs-string">"helps"</span>, <span class="hljs-string">"prefers"</span>, <span class="hljs-string">"sends"</span>, <span class="hljs-string">"plays with"</span>, <span class="hljs-string">"messes up with"</span>],
        <span class="hljs-string">"Vintr"</span>: [<span class="hljs-string">"coughs"</span>, <span class="hljs-string">"daydreams"</span>, <span class="hljs-string">"whines"</span>, <span class="hljs-string">"slobbers"</span>, <span class="hljs-string">"appears"</span>, <span class="hljs-string">"disappears"</span>, <span class="hljs-string">"exists"</span>, <span class="hljs-string">"cries"</span>, <span class="hljs-string">"laughs"</span>]
    }

    <span class="hljs-keyword">let</span> grammar = tracery.createGrammar(data);
    <span class="hljs-keyword">let</span> expansion = grammar.flatten(<span class="hljs-string">'#start#'</span>);

    sentences.push(expansion);

    printSentences(sentences);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printSentences</span>(<span class="hljs-params">sentences</span>) </span>{
    <span class="hljs-keyword">let</span> textBox = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"sentences"</span>);
    textBox.innerHTML = <span class="hljs-string">""</span>;
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i=sentences.length<span class="hljs-number">-1</span>; i&gt;=<span class="hljs-number">0</span>; i--) {
        textBox.innerHTML += <span class="hljs-string">"&lt;p&gt;"</span>+sentences[i]+<span class="hljs-string">"&lt;/p&gt;"</span>
    }
}
</code></pre>
<p>Once you have finished writing the code, run your HTML file. It should look something like this.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/01/ws2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Every time you click the red button it will generate a sentence. Some of these sentences might not make any sense. This is because, as I said earlier, CFGs cannot describe the context and some other features that natural languages possess. It is used only to define the syntax and structure of the sentences. </p>
<p>You can check out the live version of this <a target="_blank" href="https://aditya2000.github.io/weird-sentences/">here</a>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>If you have made it this far, I highly appreciate your resilience. It might be a new concept for some of you, and others might have learnt about it in their college courses. But still, Context Free Grammars have interesting applications that range widely from Computer Science to Linguistics. </p>
<p>I have tried my best to present the main ideas of CFGs here, but there is a lot more that you can learn about them. Here I have left links to some great resources: </p>
<ul>
<li><a target="_blank" href="https://youtu.be/C3EwsSNJeOE">Context Free Grammars</a> by Daniel Shiffman.</li>
<li><a target="_blank" href="https://youtu.be/R_OVyFrBhiU">Context Free Grammars Examples</a> by Fullstack Academy</li>
<li><a target="_blank" href="https://github.com/galaxykate/tracery">Tracery</a> by Galaxykate</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Finite State Machine Explained ]]>
                </title>
                <description>
                    <![CDATA[ The finite state machine (FSM) is a software design pattern where a given model transitions to other behavioral states through external input. Understanding the Finite State Machine A FSM is defined by its states, its initial state and the transition... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/finite-state-machines/</link>
                <guid isPermaLink="false">66c34a66a1d481faeda49b42</guid>
                
                    <category>
                        <![CDATA[ design patterns ]]>
                    </category>
                
                    <category>
                        <![CDATA[ finite state machine ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 06 Jan 2020 22:37:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9e19740569d1a4ca3b56.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The finite state machine (FSM) is a software design pattern where a given model transitions to other behavioral states through external input.</p>
<h2 id="heading-understanding-the-finite-state-machine"><strong>Understanding the Finite State Machine</strong></h2>
<p>A FSM is defined by its <strong>states</strong>, its <strong>initial state</strong> and the <strong>transitions</strong>.</p>
<p>The power of FSM comes from the ability to clearly define different <em>behaviors</em> in different conditions. Usually FSM is used with looping behavioral scripts which constantly evaluate the current situation in a loop or with events.</p>
<p>To help form an image of how this might be applied, a coffee machine will be used as an example of a finite state machine. We will also cover a state diagram to visualise the FSM and provide coding examples.</p>
<h3 id="heading-state-diagram"><strong>State Diagram</strong></h3>
<p><img src="https://raw.githubusercontent.com/arunma/blogimages/master/AkkaFSM/CoffeeMachineFSM.png" alt="Coffee machine finite state machine diagram" width="1276" height="821" loading="lazy"></p>
<p>This diagram shows three possible states for the coffee machine:</p>
<ul>
<li>Open</li>
<li>ReadyToBuy</li>
<li>PoweredOff</li>
</ul>
<p>The lines between these states show which transitions are possible between states and in which direction. These transitions have conditions for when the FSM needs to change between states.</p>
<ul>
<li>StartUpMachine From the PoweredOff state to the Open state the machine has to start up. This is done manually in this case.</li>
<li>deposit &gt;= cost of coffee The FSM evaluates the amount of deposited cash either in a loop or when the amount changes (recommended in this case) If you deposit enough cash into the coffee machine, the FSM will go from ‘Open’ to ‘ReadyToBuy’.</li>
<li>ShutdownMachine The machine will automatically go from Open to PoweredOff through the ShutDownMachine method if the condition ‘no more coffees left’ is met.</li>
<li>DispenseCoffee In the ReadyToBuy state the user can buy a coffee whereafter it will be brewed and dispensed. The condition is when the BuyCoffee event (!Link to observer pattern!) fires. (not shown in diagram)</li>
<li>CancelCoffee If the user opts to cancel, the machine will go from ReadyToBuy to Open.</li>
<li>ShutDownMachine The machine will go to PoweredOff state</li>
</ul>
<h2 id="heading-states">States</h2>
<p>In every state there is defined behavior which will only be executed when the object is in that state. For instance, during PoweredOff the coffee machine won’t brew coffee before it’s powered on, during the Open state it will wait either until there’s enough cash inserted, until the power down command is given, or until it runs out of coffee. During this Open state it can do routines such as cleaning which won’t happen in other states.</p>
<h3 id="heading-initial-state"><strong>Initial State</strong></h3>
<p>Every FSM has an initial state, this means which state it starts in when it is created and has to be defined when constructed or instantiated. Of course it’s possible to directly change state if conditions are met.</p>
<h3 id="heading-transitions"><strong>Transitions</strong></h3>
<p>Every state either constantly evaluates if it should transition to another state or will transition to another state based on a triggered event.</p>
<h2 id="heading-dfa-and-nfa"><strong>DFA and NFA</strong></h2>
<p>There are two types of finite automaton, Deterministic (DFA) and Nondeterministic (NFA). Both of them accept regular languages and operate more or less in the same way described above however with some differences.</p>
<p>A DFA accepts or rejects a string of symbols and only produces one unique computation or automaton for each input string. <em>Deterministic</em> refers to the uniqueness of the computation. A Finite State Machine is called a DFA if it obeys the following rules:</p>
<ol>
<li>Each of its transitions is <em>uniquely</em> determined by its source state and input symbol</li>
<li>Reading an input symbol is required for each state transition.</li>
</ol>
<p>An NFA does not need to obey these restrictions, meaning that each DFA is also an NFA. And since they both only recognize regular languages, each NFA can be converted into an equivalent DFA using the powerset construction algorithm.</p>
<p>So what sort of rules can we expect to find in NFAs but not DFAs ?</p>
<ol>
<li>An NFA can have an <em>empty string</em> transition (generally denoted by an epsilon). Meaning that when at a certain state with an epsilon for a transition rule, the machine can transition to the next state without reading an input symbol</li>
<li>In an NFA, each pair of state and transition symbol can have multiple destination states as opposed to the unique destinations of pairs in DFAs</li>
<li>Each pair of state and transition symbol produces a ‘branch’ of computation for each of its possible destination creating some sort of a multithreaded system.</li>
<li>A DFA will reject the input string if it lands on any state other than the acceptance state. In an NFA, we only need one ‘branch’ to land on an acceptance state in order to accept the string.</li>
</ol>
<p>If you want to learn more, here's a <a target="_blank" href="https://www.freecodecamp.org/news/state-machines-basics-of-computer-science-d42855debc66/">great in-depth guide on state machines</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Kissing the state machine goodbye ]]>
                </title>
                <description>
                    <![CDATA[ By Bertil Muth Recently, I have written about simplifying an event sourced application. The article starts with code from a talk by Jakub Pilimon and Kenny Bastani. And it ends with building a model  for events in the code: how they are applied, and ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/kissing-the-state-machine-goodbye/</link>
                <guid isPermaLink="false">66d45de04a7504b7409c334b</guid>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Event Sourcing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ finite state machine ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Statecharts ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 27 Jun 2019 21:05:06 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/06/Kissing.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Bertil Muth</p>
<p>Recently, I have written about <a target="_blank" href="https://www.freecodecamp.org/news/simplifying-an-event-sourced-application/">simplifying an event sourced application</a>.</p>
<p>The article starts with <a target="_blank" href="https://gitlab.com/pilloPl/eventsourced-credit-cards/blob/4329a0aac283067f1376b3802e13f5a561f18753/src/main/java/io/pillopl/eventsourcing/">code</a> from a <a target="_blank" href="https://youtu.be/r7AGQsM7ncA">talk</a> by Jakub Pilimon and Kenny Bastani. And it ends with building a model  for events in the code: how they are applied, and under which  conditions.</p>
<p>The sample application is about Credit Card management. You can:</p>
<ul>
<li><strong>Assign a credit limit</strong>. But only once, otherwise the application throws an <code>IllegalStateException</code>.</li>
<li><strong>Withdraw money</strong>. But you can't make more than 45 withdrawals in a certain cycle. Or you'll get an exception as well.</li>
<li><strong>Repay money</strong></li>
</ul>
<p>I played around with the <code>CreditCard</code> class. I had a feeling that something might be wrong with the <code>withdraw</code> method. So I wrote a test that checks for the correct behavior.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Test(expected = IllegalStateException.class)</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">withdrawWithoutLimitAssignedThrowsIllegalStateException</span><span class="hljs-params">()</span> </span>{
    CreditCard card = <span class="hljs-keyword">new</span> CreditCard(UUID.randomUUID());
    card.withdraw(BigDecimal.ZERO);
}
</code></pre>
<p>The test attempts to withdraw an amount of zero. But no credit limit  has been assigned before. The application should reject this, and throw  an <code>IllegalStateException</code>.<br>Instead, the application threw a <code>NullPointerException</code>.</p>
<p>The application assumed that the limit had been assigned before.<br>Now: this is a sample application. If it covered all cases it probably wouldn't be as understandable as it is.</p>
<p>Let's pretend we're dealing with a real world application. What if  the required order of commands/events depends on a multitude of  conditions and states?</p>
<p>If you have ever tried to implement this with conditional statements  only, you probably know it's easy to lose the overview. But there is a  standard solution for managing complicated flows and changes in  behavior.</p>
<h2 id="heading-state-machine-to-the-rescue">State machine to the rescue</h2>
<p>In computer science, state machines have been around for decades.  They are well understood in theory. They are battle proven in practice.  They are the de facto standard for dealing with state dependent  behavior.</p>
<p>So I decided to create a UML state machine model for the sample  application. I asked myself first: Do I want to deal with commands or  events in the state machine?</p>
<p>Commands are about something the application should do in the future.<br>Events are about something that has happened in the past.</p>
<p>I wanted to <em>prevent</em> withdrawals without a credit limit assigned.<br>So the state machine model needed to deal with commands. </p>
<p>The syntax of a transition in the diagram is <code>command[condition] / commandHandler()</code>. It means: when a command object has been received, and the condition is  fulfilled if present, handle the command and go to the next state.</p>
<p><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--IsFVxafc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/3laq9tz8h82nwvjsmugv.png" alt="State machine" width="600" height="400" loading="lazy"></p>
<p>The model fixes what is allowed to happen, and what not. For example: repaying is only possible after withdrawing.</p>
<p>But that precision has a price. If you want the state machine model  to be executed and to control the behavior at runtime, you need to model  every possible transition from every state. Including its condition, if  there are two transitions with the same event.</p>
<p>That's why there is a lot more repetition in the state machine than in the original code with the <code>if</code> statements. A way to reduce the amount of repetition is to use <em>super states</em> and <em>sub states</em>:</p>
<p><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--CCZSYf5s--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/2cwl67ddaa64l2szlp4s.png" alt="State machine with sub states" width="600" height="400" loading="lazy"></p>
<p>It is easy to define state dependent behavior in a state machine model. But a state independent rule like <em>in any state (when condition X holds), do Y</em> leads to several transitions. For example, I needed to add <code>requestToCloseCycle</code> to every super state.</p>
<p>You need people with the right skills to create the models. And it's  not easy to communicate about the models with non-technical  stakeholders. It's not the way they normally speak about user journeys.</p>
<h2 id="heading-saying-goodbye">Saying goodbye</h2>
<p>It seems there are two options so far.</p>
<p>In the left corner: the <code>if</code> statement. Easy to start  with. Low overhead. Best fit for applications that have no complicated  flows of behavior. But it's easy to lose the overview when the behavior  gets complicated.</p>
<p>In the right corner: the executable state machine model. Powerful.  Proven. Precise. Gives you an overview of the behavior. But it's hard to  define state independent rules. And state machine models are difficult  to communicate about with non-technical stakeholders.</p>
<p>I stand in the third corner. I have found an alternative to state machines.<br>A solution that</p>
<ul>
<li>enables you to define conditions. But you don't have to in most cases.</li>
<li>makes state dependent and independent rules equally easy to specify.</li>
<li>uses language that all stakeholders can relate to.</li>
</ul>
<p>Before I dig into the details, here's the sample state machine model rewritten using that solution:</p>
<pre><code class="lang-java">Model model = Model.builder()
  .useCase(useCreditCard)
    .basicFlow()
        .step(assigningLimit).user(requestsToAssignLimit).systemPublish(assignedLimit)
        .step(withdrawingCard).user(requestsWithdrawingCard).systemPublish(withdrawnCard).reactWhile(accountIsOpen)
        .step(repaying).user(requestsRepay).systemPublish(repay).reactWhile(accountIsOpen)

    .flow(<span class="hljs-string">"Withdraw again"</span>).after(repaying)
        .step(withdrawingCardAgain).user(requestsWithdrawingCard).systemPublish(withdrawnCard)
        .step(repeating).continuesAt(withdrawingCard)

    .flow(<span class="hljs-string">"Cycle is over"</span>).anytime()
        .step(closingCycle).on(requestToCloseCycle).systemPublish(closedCycle)

    .flow(<span class="hljs-string">"Limit can only be assigned once"</span>).condition(limitAlreadyAssigned)
        .step(assigningLimitTwice).user(requestsToAssignLimit).system(throwsAssignLimitException)

    .flow(<span class="hljs-string">"Too many withdrawals"</span>).condition(tooManyWithdrawalsInCycle) 
        .step(withdrawingCardTooOften).user(requestsWithdrawingCard).system(throwsTooManyWithdrawalsException)
.build();
<span class="hljs-keyword">return</span> model;
</code></pre>
<p>As you can see, the model is <a target="_blank" href="https://github.com/bertilmuth/requirementsascode/blob/master/requirementsascodeexamples/creditcard_eventsourcing/src/main/java/creditcard_eventsourcing/model/CreditCardAggregateRoot.java">in the code</a>.  A model runner executes this model. The runner reacts to commands/events, similar to a state machine.</p>
<p>The basic flow is the "happy day scenario". The steps of a user to  reach her goal. The other flows cover alternative and error scenarios.</p>
<p>A flow can define an <em>explicit condition</em> for its first step to run - e.g. <code>after(...)</code>, <code>anytime()</code> or <code>condition()</code> in the sample.<br>If a flow has an explicit condition, the flow starts when the condition  is fulfilled and the runner is currently in a different flow.<br>If a flow has no explicit condition (e.g. the basic flow in the sample),  the first step runs after the runner has started, when no step has been  run so far.</p>
<p>Starting with the second step of a flow, each step has an <em>implicit condition</em>.  That condition is: run the step after the previous step in the same  flow, unless a different flow with an explicit condition can start.<br>So in contrast to state machines, you don't need to specify the conditions after the first step.</p>
<p>Internally, state depending behavior is realized by checking a condition.<br>Every step contains its complete condition that defines exactly when the step can run. That's how <a target="_blank" href="https://github.com/bertilmuth/requirementsascode">requirements as code</a> can treat state dependent and independent behavior alike.</p>
<p>Have a look at <a target="_blank" href="https://github.com/bertilmuth/requirementsascode/tree/master/requirementsascodeexamples/helloworld">further examples</a> to dig deeper.</p>
<h2 id="heading-when-to-use-requirements-as-code">When to use requirements as code</h2>
<p>Many applications have dynamic internal behavior. This is true for  distributed applications in particular. They need to deal with the fact  that "the other party" is not available.</p>
<p>But from a user's perspective, these applications look quite  predictable and regular. When I want to watch a show on Netflix or  Amazon Prime, I follow the exact same steps each time until I can watch  it. It looks like one step just follows the other.</p>
<p>That's the sweet spot for requirements as code, if used as an alternative to a state machine: defining the <em>visible behavior</em> of an application.</p>
<h2 id="heading-how-the-credit-card-application-works-now">How the Credit Card application works now</h2>
<ul>
<li>A <a target="_blank" href="https://github.com/bertilmuth/requirementsascode/blob/master/requirementsascodeexamples/creditcard_eventsourcing/src/main/java/creditcard_eventsourcing/EventsourcingApplication.java">client</a> sends a command to the <code>CreditCardAggregateRoot</code></li>
<li>The <a target="_blank" href="https://github.com/bertilmuth/requirementsascode/blob/master/requirementsascodeexamples/creditcard_eventsourcing/src/main/java/creditcard_eventsourcing/model/CreditCardAggregateRoot.java">CreditCardAggregateRoot</a> uses the event repository to replay all the events for the credit card, to restore it</li>
<li>The <code>CreditCardAggregateRoot</code> uses the above model to dispatch the command to a command handling method</li>
<li>The command handling method produces an event and applies it to the <code>CreditCard</code> instance.</li>
<li>The event handling model of the <a target="_blank" href="https://github.com/bertilmuth/requirementsascode/blob/master/requirementsascodeexamples/creditcard_eventsourcing/src/main/java/creditcard_eventsourcing/model/CreditCard.java">CreditCard</a> instance dispatches the event to a state changing method</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope you enjoyed my article. I also want to invite you to look at <a target="_blank" href="https://github.com/bertilmuth/requirementsascode">the library</a> that I used throughout the article. Try it out in practice, and let me know the result.</p>
<p><em>If you want to keep up with what I'm doing or drop me a note, follow me on <a target="_blank" href="https://www.linkedin.com/in/bertilmuth/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/BertilMuth">Twitter</a>. To learn about agile software development, visit my <a target="_blank" href="https://skl.sh/2Cq497P">online course</a>.</em><br><em>Last edited April 27, 2020: updated event sourcing process</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Understanding State Machines ]]>
                </title>
                <description>
                    <![CDATA[ By Mark Shead An intro to Computer Science concepts Computer science enables us to program, but it is possible to do a lot of programming without understanding the underlying computer science concepts. This isn’t always a bad thing. When we program, ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/state-machines-basics-of-computer-science-d42855debc66/</link>
                <guid isPermaLink="false">66c35fcdc337fbd10a4b596b</guid>
                
                    <category>
                        <![CDATA[ Computer Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ finite state machine ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Software Engineering ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 11 Feb 2018 23:02:53 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*3QzqRMfRCh28-xe1." medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Mark Shead</p>
<h4 id="heading-an-intro-to-computer-science-concepts">An intro to Computer Science concepts</h4>
<p>Computer science enables us to program, but it is possible to do a lot of programming without understanding the underlying computer science concepts.</p>
<p>This isn’t always a bad thing. When we program, we work at a much higher level of abstraction.</p>
<p>When we drive a car, we only concern ourselves with two or three pedals, a gearshift, and a steering wheel. You can safely operate a car without having any clear idea of how it works.</p>
<p>However, if you want to operate a car at the very limits of its capabilities, you need to know a lot more about automobiles than just the three pedals, gearshift and steering wheel.</p>
<p>The same is true of programming. A lot of everyday work can be accomplished with little or no understanding of computer science. You don’t need to understand computational theory to build a “Contact Us” form in PHP.</p>
<p>However, if you plan to write code that requires serious computation, you will need to understand a bit more about how computation works under the hood.</p>
<p>The purpose of this article is to provide some fundamental background for computation. If there is interest, I may follow up with some more advanced topics, but right now I want to look at the logic behind one of the simplest abstract computational devices — a <strong>finite state machine</strong>.</p>
<h3 id="heading-finite-state-machines">Finite State Machines</h3>
<p>A finite state machine is a mathematical abstraction used to design algorithms.</p>
<p>In simpler terms, a state machine will read a series of inputs. When it reads an input, it will switch to a different state. Each state specifies which state to switch to, for a given input. This sounds complicated but it is really quite simple.</p>
<p>Imagine a device that reads a long piece of paper. For every inch of paper there is a single letter printed on it–either the letter ‘a’ or the letter ‘b’.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0*xO3Fuvo1mL-jczfC." alt="Image" width="463" height="94" loading="lazy">
<em>A paper tape, with eight letters printed on it</em></p>
<p>As the state machine reads each letter, it changes state. Here is a very simple state machine:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0*msRB3BVpVkGVgEOd." alt="Image" width="304" height="183" loading="lazy"></p>
<p>The circles are “<strong>states</strong>” that the machine can be in. The arrows are the <strong>transitions</strong>. So, if you are in state <em>s</em> and read an ‘a’, you’ll transition to state <em>q</em>. If you read a ‘b’, you’ll stay in state <em>s</em>.</p>
<p>So if we start on <em>s</em> and read the paper tape above from left to right, we will read the ‘a’ and move to state <em>q</em>.</p>
<p>Then, we’ll read ‘b’ and move back to state <em>s</em>.</p>
<p>Another ‘b’ will keep us on <em>s</em>, followed by an ‘a’ — which moves us back to the <em>q</em> state. Simple enough, but what’s the point?</p>
<p>Well, it turns out that you can run a tape through the state machine and tell something about the sequence of letters, by examining the state you end up on.</p>
<p>In our simple state machine above, if we end in state <em>s</em>, the tape must end with a letter ‘b’. If we end in state <em>q</em>, the tape ends with the letter ‘a’.</p>
<p>This may sound pointless, but there are an <em>awful lot</em> of problems that can be solved with this type of approach. A very simple example would be to determine if a page of HTML contains these tags in this order:</p>
<pre><code>&lt;html&gt;   <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span></span>   <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span></span> &lt;/html&gt;
</code></pre><p>The state machine can move to a state that shows it has read the html tag, loop until it gets to the head tag, loop until it gets to the head close tag, and so on.</p>
<p>If it successfully makes it to the final state, then you have those particular tags in the correct order.</p>
<p>Finite state machines can also be used to represent many other systems — such as the mechanics of a parking meter, pop machine, automated gas pump, and all kinds of other things.</p>
<h3 id="heading-deterministic-finite-state-machines">Deterministic Finite State Machines</h3>
<p>The state machines we’ve looked at so far are all <strong>deterministic</strong> state machines. From any state, there is only <em>one</em> transition for any allowed input. In other words, there can’t be two paths leading out of a state when you read the letter ‘a’. At first, this sounds silly to even make this distinction.</p>
<p>What good is a set of decisions if the same input can result in moving to more than one state? You can’t tell a computer, <code>if x == true</code> then execute <code>doSomethingBig</code> or execute <code>doSomethingSmall</code>, can you?</p>
<p>Well, you kind of can with a state machine.</p>
<p>The output of a state machine is its final state. It goes through all its processing, and then the final state is read, and <strong>then</strong> an action is taken. A state machine doesn’t <strong>do</strong> anything as it moves from state to state.</p>
<p>It processes, and when it gets to the end, the state is read and something external triggers the desired action (for example, dispensing a soda can). This is an important concept when it comes to <strong>non-deterministic</strong> finite state machines.</p>
<h3 id="heading-non-deterministic-finite-state-machines">Non-deterministic Finite State Machines</h3>
<p>Non-deterministic finite state machines are finite state machines where a given input from a particular state can lead to <strong>more than one</strong> different state.</p>
<p>For example, let’s say we want to build a finite state machine that can recognize strings of letters that:</p>
<ul>
<li>Start with the letter ‘a’</li>
<li>and are then followed by zero or more occurrences of the letter ‘b’</li>
<li>or, zero or more occurrences of the letter ‘c’</li>
<li>are terminated by the next letter of the alphabet.</li>
</ul>
<p>Valid strings would be:</p>
<ul>
<li>abbbbbbbbbc</li>
<li>abbbc</li>
<li>acccd</li>
<li>acccccd</li>
<li>ac (zero occurrences of b)</li>
<li>ad (zero occurrences of c)</li>
</ul>
<p>So it will recognize the letter ‘a’ followed by zero or more of the same letter of ‘b’ or ‘c’, followed by the next letter of the alphabet.</p>
<p>A very simple way to represent this is with a state machine that looks like the one below, where a final state of <em>t</em> means that the string was accepted and matches the pattern.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0*3QzqRMfRCh28-xe1." alt="Image" width="417" height="360" loading="lazy">
<em>Pattern matching finite state machine</em></p>
<p>Do you see the problem? From starting point <em>s</em>, we don’t know which path to take. If we read the letter ‘a’, we don’t know whether to go to the state <em>q</em> or <em>r.</em></p>
<p>There are a few ways to solve this problem. One is by backtracking. You simply take all the possible paths, and ignore or back out of the ones where you get stuck.</p>
<p>This is basically how most chess playing computers work. They look at all the possibilities — and all the possibilities of those possibilities — and choose the path that gives them the greatest number of advantages over their opponent.</p>
<p>The other option is to convert the non-deterministic machine into a deterministic machine.</p>
<p>One of the interesting attributes of a non-deterministic machine is that there exists an algorithm to turn any non-deterministic machine into a deterministic one. However, it is often much more complicated.</p>
<p>Fortunately for us, the example above is only slightly more complicated. In fact, this one is simple enough that we can transform it into a deterministic machine in our head, without the aid of a formal algorithm.</p>
<p>The machine below is a deterministic version of the non-deterministic machine above. In the machine below, a final state of <em>t</em> or <em>v</em> is reached by any string that is accepted by the machine.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/0*Sp_eR3qz6X2w-vPo." alt="Image" width="337" height="405" loading="lazy">
<em>A deterministic finite state machine</em></p>
<p>The non-deterministic model has four states and six transitions. The deterministic model has six states, ten transitions and two possible final states.</p>
<p>That isn’t that much more, but complexity usually grows exponentially. A moderately sized non-deterministic machine can produce an absolutely <em>huge</em> deterministic machine.</p>
<h3 id="heading-regular-expressions">Regular Expressions</h3>
<p>If you have done any type of programming, you’ve probably encountered regular expressions. Regular expressions and finite state machines are functionally equivalent. Anything you can accept or match with a regular expression, can be accepted or matched with a state machine.</p>
<p>For example, the pattern described above could be matched with the regular expression: <code>a(b*c|c*d)</code></p>
<p>Regular expressions and finite state machines also have the same limitations. In particular, they both can only match or accept patterns that can be handled with finite memory.</p>
<p>So what type of patterns can’t they match? Let’s say you want to only match strings of ‘a’ and ‘b’, where there are a number of ‘a’s followed by an equal number of ‘b’s. Or <em>n</em> ‘a’s followed by <em>n</em> ‘b’s, where <em>n</em> is some number.</p>
<p>Examples would be:</p>
<ul>
<li>ab</li>
<li>aabb</li>
<li>aaaaaabbbbbb</li>
<li>aaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbb</li>
</ul>
<p>At first, this looks like an easy job for a finite state machine. The problem is that you’ll quickly run out of states, or you’ll have to assume an infinite number of states — at which point it is no longer a <em>finite</em> state machine.</p>
<p>Let’s say you create a finite state machine that can accept up to 20 ‘a’s followed by 20 ‘b’s. That works fine, until you get a string of 21 ‘a’s followed by 21 ‘b’s — at which point you will need to rewrite your machine to handle a longer string.</p>
<p>For any string you can recognize, there is one just a little bit longer that your machine can’t recognize because it runs out of memory.</p>
<p>This is known as the <strong>Pumping Lemma</strong> which basically says: “if your pattern has a section that can be repeated (like the one) above, then the pattern is not regular”.</p>
<p>In other words, neither a regular expression nor a finite state machine can be constructed that will recognize all the strings that <em>do</em> match the pattern.</p>
<p>If you look carefully, you’ll notice that this type of pattern where every ‘a’ has a matching ‘b’, looks very similar to HTML. Within any pair of tags, you may have any number of other matching pairs of tags.</p>
<p>So, while you may be able to use a regular expression or finite state machine to recognize if a page of HTML has the <code>&lt;ht</code>ml<code>&gt;,</code> `; and  elements in the correct order, you can’t use a regular expression to tell if an entire HTML page is valid or not — because HTML is not a regular pattern.</p>
<h3 id="heading-turing-machines">Turing Machines</h3>
<p>So how do you recognize <strong>non-regular patterns</strong>?</p>
<p>There is a theoretical device that is similar to a state machine, called a Turing Machine. It is similar to a finite state machine in that it has a paper strip which it reads. But, a Turing Machine can erase and write on the paper tape.</p>
<p>Explaining a Turing Machine will take more space that we have here, but there are a few important points relevant to our discussion of finite state machines and regular expressions.</p>
<p>Turing Machines are <strong>computationally complete</strong> — meaning anything that can be computed, can be computed on a Turing Machine.</p>
<p>Since a Turing Machine can write as well as read from the paper tape, it is not limited to a finite number of states. The paper tape can be assumed to be infinite in length. Of course, actual computers don’t have an infinite amount of memory. But, they usually do contain enough memory so you don’t hit the limit for the type of problems they process.</p>
<p>Turing Machines give us an imaginary mechanical device that lets us visualize and understand how the computational process works. It is particularly useful in understanding the limits of computation. If there is interest I’ll do another article on Turing Machines in the future.</p>
<h3 id="heading-why-does-this-matter">Why does this matter?</h3>
<p>So, what’s the point? How is this going to help you create that next PHP form?</p>
<p>Regardless of their limitations, state machines are a very central concept to computing. In particular, it is significant that for any non-deterministic state machine you can design, there exists a deterministic state machine that does the same thing.</p>
<p>This is a key point, because it means you can design your algorithm in whichever way is the easiest to think about. Once you have a working algorithm, you can convert it into whatever form is most efficient.</p>
<p>The understanding that finite state machines and regular expressions are functionally equivalent opens up some incredibly interesting uses for regular expression engines — particularly when it comes to creating business rules that can be changed without recompiling a system.</p>
<p>A foundation in Computer Science allows you to take a problem you don’t know how to solve and reason: “I don’t know how to solve X, but I do know how to solve Y. And I know how to convert a solution for Y into a solution for X. Therefore, I now know how to solve X.”</p>
<p>If you like this article, you might enjoy my <a target="_blank" href="https://www.youtube.com/markshead">YouTube channel</a> where I create an occasional video or cartoon about some aspect of creating software. I also have a <a target="_blank" href="http://eepurl.com/uPj05">mailing list</a> for people who would like an occasional email when I produce something new.</p>
<p>Originally published at <a target="_blank" href="https://blog.markshead.com/869/state-machines-computer-science/">blog.markshead.com</a> on February 11, 2018.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
