<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Morgan Kenyon</title>
    <description>The latest articles on Forem by Morgan Kenyon (@mokenyon).</description>
    <link>https://forem.com/mokenyon</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F210506%2F739ee39c-cda6-4e8c-860c-f7fb67b366c3.jpg</url>
      <title>Forem: Morgan Kenyon</title>
      <link>https://forem.com/mokenyon</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/mokenyon"/>
    <language>en</language>
    <item>
      <title>Supervised v. Unsupervised v. Reinforcement Learning: An Introduction</title>
      <dc:creator>Morgan Kenyon</dc:creator>
      <pubDate>Mon, 18 May 2020 00:38:41 +0000</pubDate>
      <link>https://forem.com/mokenyon/supervised-v-unsupervised-v-reinforcement-learning-an-introduction-451m</link>
      <guid>https://forem.com/mokenyon/supervised-v-unsupervised-v-reinforcement-learning-an-introduction-451m</guid>
      <description>&lt;p&gt;Machine Learning powers a lot of what we do. Currently there are three main categories of machine learning, supervised learning, unsupervised learning and reinforcement learning.&lt;/p&gt;

&lt;p&gt;Let’s talk a bit about them and what differentiates them.&lt;/p&gt;

&lt;h2&gt;
  
  
  Machine Learning
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;Machine learning (ML) is the scientific study of algorithms and statistical models that computer systems use to perform a specific task without using explicit instructions. ~ &lt;a href="https://en.wikipedia.org/wiki/Machine_learning"&gt;Wikipedia&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I am a professional software developer who mainly writes web apps.&lt;/p&gt;

&lt;p&gt;When I want a computer to do something, I have to explicitly code for that. If I don’t tell a computer to do something it will never do it.&lt;/p&gt;

&lt;p&gt;Machine Learning on the other hand, allows computers to perform tasks that they themselves learn.&lt;/p&gt;

&lt;p&gt;You throw data at a computer and it learns patterns from that data. (hopefully)&lt;/p&gt;

&lt;p&gt;This has substantial power and also drawbacks. At times computers can surprise or surpass our intellect, but there are lot of tasks computers can’t currently solve.&lt;/p&gt;

&lt;p&gt;Broadly speaking, there are three main categories of machine learning:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Supervised Learning&lt;/li&gt;
&lt;li&gt;Unsupervised Learning&lt;/li&gt;
&lt;li&gt;Reinforcement Learning&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Supervised Learning
&lt;/h2&gt;

&lt;p&gt;Our first category is supervised learning. For me personally, this is the easiest category to learn and understand.&lt;/p&gt;

&lt;p&gt;In supervised learning, the data that the algorithm trains on has both input and output.&lt;/p&gt;

&lt;p&gt;One good example of this is the &lt;a href="http://yann.lecun.com/exdb/mnist/"&gt;MNIST Database of Handwritten Digits&lt;/a&gt;, the “hello world” of machine learning. This database is a collection of handwritten digits in input and output pairs. The input is the image, and the output is the answer of what digit is in the photo.&lt;/p&gt;

&lt;p&gt;When using supervised learning, the algorithm uses the input to make a prediction and compares the prediction against the expected output.&lt;/p&gt;

&lt;p&gt;If it’s incorrect, the algorithm will modify itself in some way to make better predictions in the future.&lt;/p&gt;

&lt;p&gt;Supervised learning is powerful and simple if you have the data that you need. If you don’t have neatly labeled data, or if your data is poorly labeled, then supervised learning is not going to be as effective.&lt;/p&gt;

&lt;h2&gt;
  
  
  Unsupervised Learning
&lt;/h2&gt;

&lt;p&gt;Our next category is unsupervised learning. In contrast to supervised learning, unsupervised learning has input but no expected output.&lt;/p&gt;

&lt;p&gt;Unsupervised algorithms automatically learning patterns or groupings that exist in the data.&lt;/p&gt;

&lt;p&gt;For instance, in a &lt;a href="https://www.wired.com/2012/06/google-x-neural-network/"&gt;2012 Google study&lt;/a&gt;, researches just threw 10 million YouTube thumbnails at their “brain.” Over the course of three days it began to recognize pictures of cats.&lt;/p&gt;

&lt;p&gt;No one told the brain to look for cats or recognize cats. Cats all look rather similar, so the brain remembered that pattern and taught itself how to identify it.&lt;/p&gt;

&lt;p&gt;It’s also how a lot of modern NLP models are trained. Just throw lots of text (like the entire English wikipedia) at it and allow it to figure out how to make sense of it.&lt;/p&gt;

&lt;p&gt;Unsupervised learning is great when you have a lot of data and a lot of compute power to find patterns in your data.&lt;/p&gt;

&lt;h2&gt;
  
  
  Reinforcement Learning
&lt;/h2&gt;

&lt;p&gt;Reinforcement learning tries to model problems similarly to the way that humans live our lives. Reinforcement learning learns how to optimize an agents behavior based on the presence or absence of some reward.&lt;/p&gt;

&lt;p&gt;For instance in my real life, I go to work because I receive a paycheck every two weeks. The reward (the paycheck) influences my behavior (continuing to be a good employee).&lt;/p&gt;

&lt;p&gt;A good example is game playing bots. There’s an environment (the board), the agent takes actions, and receives a reward at the end of the game (win, loss or tie). The agent plays a lot of games to learn what actions lead to better rewards.&lt;/p&gt;

&lt;p&gt;One good example of this is &lt;a href="https://deepmind.com/research/publications/playing-atari-deep-reinforcement-learning"&gt;DeepMind&lt;/a&gt; learning to &lt;a href="https://www.youtube.com/watch?v=V1eYniJ0Rnk"&gt;play Atari games&lt;/a&gt;. Raw pixel data was fed into the rl algorithm, it’s reward function was the game score, and it learned how to “play” the game to improve it’s reward.&lt;/p&gt;

&lt;h2&gt;
  
  
  Deep Learning
&lt;/h2&gt;

&lt;p&gt;One last thing that’s worth mentioning is deep learning. Deep Learning is a sub domain of all of these categories. The label Deep Learning can be applied to any algorithm that specifically uses a multi-layer neural network, a deep network.&lt;/p&gt;

&lt;p&gt;For instance, there are numerous ways to solve problems using reinforcement learning. If you’re specifically using a neural network, then you can say you’re using deep reinforcement learning.&lt;/p&gt;

&lt;p&gt;If you’re playing around with neural networks, you can usually call it “deep”. But if you’re using some other machine learning algorithm to solve your problem, you wouldn’t call it “deep.”&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Thoughts
&lt;/h2&gt;

&lt;p&gt;Machine Learning is an exciting field. If you’re just starting out with machine learning, fast.ai has a &lt;a href="https://course.fast.ai/"&gt;great free course&lt;/a&gt; to help you explain the basics. I’m currently reading &lt;a href="https://www.manning.com/books/grokking-deep-reinforcement-learning"&gt;Grokking Deep Reinforcement Learning&lt;/a&gt; to bump up my reinforcement learning!&lt;/p&gt;

&lt;p&gt;If you’re interested in learning more about machine learning, &lt;a href="https://twitter.com/mokenyon"&gt;follow me on twitter&lt;/a&gt;, I’ll be learning, writing and tweeting about it as I do it.&lt;/p&gt;

</description>
      <category>machinelearning</category>
    </item>
    <item>
      <title>Optimizing our Perfect Tic-Tac-Toe Bot</title>
      <dc:creator>Morgan Kenyon</dc:creator>
      <pubDate>Sun, 10 May 2020 18:41:23 +0000</pubDate>
      <link>https://forem.com/mokenyon/optimizing-our-perfect-tic-tac-toe-bot-4m65</link>
      <guid>https://forem.com/mokenyon/optimizing-our-perfect-tic-tac-toe-bot-4m65</guid>
      <description>&lt;p&gt;In my &lt;a href="https://thesharperdev.com/coding-the-perfect-tic-tac-toe-bot/"&gt;last post&lt;/a&gt;, we built a tic-tac-toe bot that would never lose a game! It was great, except it was really slow. It took over 30 seconds to determine the first move.&lt;/p&gt;

&lt;p&gt;Lets optimize that using a simple technique to prune the amount of searching we perform for each move!&lt;/p&gt;

&lt;h2&gt;
  
  
  Our Problem
&lt;/h2&gt;

&lt;p&gt;Why is our bot slow? It’s slow because it’s dumb. There’s no intelligence to how it goes about searching boards.&lt;/p&gt;

&lt;p&gt;Lets take the following game board.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--K0_LtUJH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/t1q065fgzcgk8bf5re7p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--K0_LtUJH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/t1q065fgzcgk8bf5re7p.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It’s X’s turn, what is X going to do? Obviously they’re going to play in the bottom right corner and win.&lt;/p&gt;

&lt;p&gt;But our bot sees 5 potential moves X can make, and evaluates each one equally. It eventually picks the bottom right corner as the best move, but not before seeing and comparing all 5 moves against each other. Evaluating all moves equally leads us to do a lot of unnecessary work, which is the main performance problem.&lt;/p&gt;

&lt;h2&gt;
  
  
  Alpha Beta Pruning – Intuitively
&lt;/h2&gt;

&lt;p&gt;If you recall back to when we discussed our &lt;a href="https://thesharperdev.com/implementing-minimax-tree-search/"&gt;minimax algorithm&lt;/a&gt;, one of our players is attempting to maximize the score and the other is attempting to minimize the score. We search the entire tree, alternating taking the max or min at that level to determine the optimal game score.&lt;/p&gt;

&lt;p&gt;Lets take the following simple tree. Player 1 has the first choice and wants to maximize their score. Player 2 will then take a turn and wants to minimize their score. And notice that our last node doesn’t have a value.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--c1aSsO5o--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/mcjg4z9o1vsz24pot331.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--c1aSsO5o--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/mcjg4z9o1vsz24pot331.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Why doesn’t our last node have a value? It’s empty to demonstrate that the value actually doesn’t matter. We don’t need that node’s value to make the optimal decision.&lt;/p&gt;

&lt;p&gt;Here’s how we would calculate it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--CK6Rqjd5--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/fqg3sp6840b0rf8wb0si.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--CK6Rqjd5--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/fqg3sp6840b0rf8wb0si.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To calculate the score for the left sub tree, we take the min(-2,3) = -2. So if we go left, we would end up with a score of -2.&lt;/p&gt;

&lt;p&gt;Evaluating the one node of the right sub tree, we find a -10. -10 is worse than our left sub tree. We would rather take that -2 score than a -10.&lt;/p&gt;

&lt;p&gt;Even though we don’t know every node’s value, we know enough to stop further exploration.&lt;/p&gt;

&lt;p&gt;That’s the core idea, stop searching down a particular tree when we are guaranteed to get a worse result than what we already have.&lt;/p&gt;

&lt;p&gt;In this example, we saved exploring one node, not a big deal. The benefit comes in avoiding having to search entire subtrees. In more complicated games, such as Chess or Go, with branching factors of ~35 or ~250, anything we can avoid searching is a win!&lt;/p&gt;

&lt;h2&gt;
  
  
  Alpha Beta Pruning Pseudocode
&lt;/h2&gt;

&lt;p&gt;Now that we’ve discussed the idea behind alpha beta pruning, lets look at the pseudocode.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The algorithm introduces two new variables, called alpha and beta (hence the name of the algorithm), that track each players current state.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;alpha – tracks the lowest score for the maximizing player, initialized to negative infinity.&lt;/li&gt;
&lt;li&gt;beta – tracks the highest score for the minimizing player, initialized to positive infinity.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Lines 12 and 20 hold the potential to stop evaluating whenever it’s useless to. Whenever the lowest score for the maximizing player (alpha) is greater than the highest score for the minimizing player (beta), we stop evaluating.&lt;/p&gt;

&lt;p&gt;If we get to the point where we realize, “hey this is worse than what we already know”, we stop searching. When we choose to stop searching down a path, we say that we’re pruning. Hence the name of the algorithm.&lt;/p&gt;

&lt;p&gt;Lets take a look at what this looks like in our tic-tac-toe bot.&lt;/p&gt;

&lt;h2&gt;
  
  
  AbBot – AlphaBeta Bot
&lt;/h2&gt;

&lt;p&gt;Lets start by taking another look at our &lt;strong&gt;invincibot&lt;/strong&gt;.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;For every board, we:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Generate the legal moves (line 27)&lt;/li&gt;
&lt;li&gt;Search down the subtree of each potential move (lines 30-36), keeping track of the value that each subtree has (candidate_choices).&lt;/li&gt;
&lt;li&gt;We only stop whenever someone either wins or the game is tied (lines 19-25)&lt;/li&gt;
&lt;li&gt;Determine the max and min moves (lines 38-41)&lt;/li&gt;
&lt;li&gt;Then return the corresponding move depending on whether the player is looking for max or min (lines 45-48)
Point #3 is the important step, we only stop when the game ends. We need a better way to stop searching.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Lets implement alpha beta pruning for our tic tac toe bot now to do that.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;You’ll notice it’s a mix of my previous bot code with the alpha beta pseudocode. Notable points are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;We initialize our alpha and beta to -100 and 100 (line 59), those values are both small/big enough for our needs.&lt;/li&gt;
&lt;li&gt;Lines 40 &amp;amp; 47 hold the potential to stop evaluating early, depending on our alpha and betas.&lt;/li&gt;
&lt;li&gt;The rest is pretty much the same.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  How Does It Perform?
&lt;/h2&gt;

&lt;p&gt;If you remember from my last post, the optimal game of tic-tac-toe always ends in a tie. When two players play against each other who always pick the best move, the game ties. It’s only when a player makes a mistake that someone will win.&lt;/p&gt;

&lt;p&gt;That’s what happened when we played our &lt;strong&gt;invincibot&lt;/strong&gt; against itself, it tied all day long.&lt;/p&gt;

&lt;p&gt;When we pit our &lt;strong&gt;abbot&lt;/strong&gt; against itself and against &lt;strong&gt;invincibot&lt;/strong&gt;, it also ties all day long.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;abbot (x) vs invincibot (o)

&lt;ul&gt;
&lt;li&gt;x wins: 0&lt;/li&gt;
&lt;li&gt;o wins: 0&lt;/li&gt;
&lt;li&gt;ties: 15&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;invincibot (x) vs abbot(o)

&lt;ul&gt;
&lt;li&gt;x wins: 0&lt;/li&gt;
&lt;li&gt;o wins: 0&lt;/li&gt;
&lt;li&gt;ties: 15&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;abbot (x) vs abbot(o)

&lt;ul&gt;
&lt;li&gt;x wins: 0&lt;/li&gt;
&lt;li&gt;o wins: 0&lt;/li&gt;
&lt;li&gt;ties: 15&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So our bot makes the same optimal choices, but what about the number of board states explored? We coded our &lt;strong&gt;abbot&lt;/strong&gt; in order to reduce the searching, which would help it play faster.&lt;/p&gt;

&lt;p&gt;Here’s the decrease in boards searched through in &lt;strong&gt;invincibot&lt;/strong&gt; compared to our abbot:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;1st move: 294,778 =&amp;gt; 12,413 =&amp;gt; ~95% decrease&lt;/li&gt;
&lt;li&gt;2nd move: 31,973 =&amp;gt; 1,675 =&amp;gt; ~95% decrease&lt;/li&gt;
&lt;li&gt;3rd move: 3,864 =&amp;gt; 525 =&amp;gt; ~86% decrease&lt;/li&gt;
&lt;li&gt;4th move: 478 =&amp;gt; 44 =&amp;gt; ~90% decrease&lt;/li&gt;
&lt;li&gt;5th move: 104 =&amp;gt; 38 =&amp;gt; ~63% decrease&lt;/li&gt;
&lt;li&gt;6th move: 26 =&amp;gt; 10&lt;/li&gt;
&lt;li&gt;7th move: 8 =&amp;gt; 6&lt;/li&gt;
&lt;li&gt;8th move: 3 =&amp;gt; 3&lt;/li&gt;
&lt;li&gt;9th move: 1 =&amp;gt; 1&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This means that roughly 95% of boards that our original bot search through for the first two moves were redundant. That’s an impressive reduction!&lt;/p&gt;

&lt;p&gt;Also when two &lt;strong&gt;abbots&lt;/strong&gt; play against each other, the games only takes about 1 sec. Whereas when two &lt;strong&gt;invincibots&lt;/strong&gt; play against each other, the games takes about 1.5 mins. Another impressive reduction.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Thoughts
&lt;/h2&gt;

&lt;p&gt;Implementing alpha-beta pruning drastically improved the performance of our bot. I really enjoyed implementing this and seeing this level of improvement.&lt;/p&gt;

&lt;p&gt;I think next week I’ll look into implementing a Monte Carlo type search for our bot. While not necessary to solve tic-tac-toe, this technique is vital in tackling more complicated games.&lt;/p&gt;

&lt;p&gt;If you’re interested in learning more about game playing bots and machine learning, &lt;a href="https://twitter.com/mokenyon"&gt;follow me on twitter&lt;/a&gt;, I’ll be learning, writing and tweeting about it as I do it.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;a href="https://github.com/morgankenyon/RandomML"&gt;Github repo&lt;/a&gt; with code samples&lt;/em&gt;.&lt;/p&gt;

</description>
      <category>python</category>
      <category>machinelearning</category>
    </item>
    <item>
      <title>Coding A Perfect Tic-Tac-Toe Bot</title>
      <dc:creator>Morgan Kenyon</dc:creator>
      <pubDate>Sun, 03 May 2020 20:10:42 +0000</pubDate>
      <link>https://forem.com/mokenyon/coding-a-perfect-tic-tac-toe-bot-2koi</link>
      <guid>https://forem.com/mokenyon/coding-a-perfect-tic-tac-toe-bot-2koi</guid>
      <description>&lt;p&gt;&lt;em&gt;This article builds upon last week’s &lt;a href="https://thesharperdev.com/implementing-minimax-tree-search/"&gt;minimax searching article&lt;/a&gt;. I won’t discuss minimax in depth here, so please check out that article if you have questions about minimax.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Games are fun! Programming computers to play games is also fun!&lt;/p&gt;

&lt;p&gt;Today I’m going to walk you through what is takes to write a tic tac toe bot.&lt;/p&gt;

&lt;p&gt;Tic tac toe might be a simple game, but it’s useful to teach strategies for how some computers approach playing games.&lt;/p&gt;

&lt;h2&gt;
  
  
  How Humans Play Tic Tac Toe
&lt;/h2&gt;

&lt;p&gt;Imagine you wanted to play tic tac toe. How would you go about doing that?&lt;/p&gt;

&lt;p&gt;You’d first learn the rules. Then start playing games.&lt;/p&gt;

&lt;p&gt;Which deciding on a move, you would probably mentally play out how the game would progress.&lt;/p&gt;

&lt;p&gt;If I play there, and he plays there, then I could play there, so on and so on.&lt;/p&gt;

&lt;p&gt;Over time, you begin to understand which strategies are better or worse.&lt;/p&gt;

&lt;p&gt;You begin to gather an intuition about the game.&lt;/p&gt;

&lt;h2&gt;
  
  
  How Bots Play Tic Tac Toe
&lt;/h2&gt;

&lt;p&gt;On the other hand, how do bots play games? It’s harder for a bot to build an “intuition” about games.&lt;/p&gt;

&lt;p&gt;Humans have to program bots how to play games. Historically that’s done via a rules or brute force based approach. Our programs tell bots exactly what to do in each circumstance. That’s changing a bit with the rise of deep learning.&lt;/p&gt;

&lt;p&gt;Today we’re going to teach our bot how to play tic tac toe using a brute force solution, &lt;a href="https://thesharperdev.com/implementing-minimax-tree-search/"&gt;minimax searching&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;We’ll leverage minimax searching to simulate every possible move and counter move. That way our bot will always pick the best move given a particular game state.&lt;/p&gt;

&lt;p&gt;This type of strategy gets computationally infeasible for more complicated games, but useful for solving games of this complexity.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setting Up Our Game
&lt;/h2&gt;

&lt;p&gt;The first thing that we’ll do is write classes and methods that keep track of our game state. All source code is located on &lt;a href="https://github.com/morgankenyon/RandomML/tree/master/src/tictactoe"&gt;github&lt;/a&gt;.&lt;/p&gt;

&lt;h5&gt;
  
  
  Player
&lt;/h5&gt;

&lt;p&gt;First, we'll define our player enum.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Tic tac toe is a two player game, so naturally we’ll have two players. We’ll also provide a useful property, &lt;code&gt;other&lt;/code&gt;, to always allow us to easily get the other player.&lt;/p&gt;

&lt;h5&gt;
  
  
  Board
&lt;/h5&gt;

&lt;p&gt;Next we’ll turn out attention towards our board. Our board handles most of the logic for running a game. It tracks the history of moves, determines when someone wins and ensures everyone plays according to the rules.&lt;/p&gt;

&lt;p&gt;We’ll start of by defining a helper, our board constructor and a print method to print our board.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;code&gt;MARKER_TO_CHAR&lt;/code&gt; allows us to convert between how we track our players and how we display them.&lt;/p&gt;

&lt;p&gt;Our constructor initializes an empty board and empty moves list.&lt;/p&gt;

&lt;p&gt;Here’s what an empty board would look like.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--BQ48wlhC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/pvnmkjextp7qbcfi3c7m.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--BQ48wlhC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/pvnmkjextp7qbcfi3c7m.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And here’s what it would look like after two turns.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1SEMYarw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/f55ji74ish137rsvg1q2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1SEMYarw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/f55ji74ish137rsvg1q2.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Definitely simple, but effective. Now lets turn out attention to determining if someone has won our game.&lt;/p&gt;

&lt;h4&gt;
  
  
  Winning
&lt;/h4&gt;

&lt;p&gt;How does someone win a game of tic tac toe? Someone wins if they get three in a row. So these are all winning moves for o.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--NRv0XJsD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/uv8d0frdxo8z957riuu4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--NRv0XJsD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/uv8d0frdxo8z957riuu4.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--d3qYHQiY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/aynn754pztptgfktx6gy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--d3qYHQiY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/aynn754pztptgfktx6gy.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1TqrDcm---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/1i7n3nxomt3jk4g3o4iv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1TqrDcm---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/1i7n3nxomt3jk4g3o4iv.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--zk3epDA2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/tx29q7s13jt7o2wzic2m.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--zk3epDA2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/tx29q7s13jt7o2wzic2m.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So we’ll add a method called &lt;code&gt;has_winner()&lt;/code&gt; to our board class that checks those 4 cases.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;We only check after our game is 5 moves or older, a tic tac toe game is unwinnable before that point.&lt;/p&gt;

&lt;p&gt;If it finds a winner it will return that player, else return &lt;code&gt;None&lt;/code&gt; indicating that there is no winner yet.&lt;/p&gt;

&lt;h4&gt;
  
  
  Helper Functions
&lt;/h4&gt;

&lt;p&gt;Then lastly we’ll wrap up our board with several helper functions.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;code&gt;make_move()&lt;/code&gt; takes a row, col and player and will mark that space for that player if the space is empty.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;get_legal_moves()&lt;/code&gt; determines which of the board spaces is unoccupied and returns those spaces in a [row, col] format.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;__deepcopy__()&lt;/code&gt;, most of the bots that we’re going to build generate copies of boards. This method helps ensure that our simulated boards don’t mess up our real board.&lt;/p&gt;

&lt;h4&gt;
  
  
  Game
&lt;/h4&gt;

&lt;p&gt;The last class we’ll introduce before diving into bots is our game class. It’s job is to simulate and record stats for games against two different bots.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;It can simulate a configurable amount of games. We’ll use this to determine how our bots fair against either other over a larger quantity of games.&lt;/p&gt;

&lt;p&gt;Now lets dive into bots!&lt;/p&gt;

&lt;h2&gt;
  
  
  RandomBot
&lt;/h2&gt;

&lt;p&gt;The first bot we’re going to build makes random moves. It’s the simplest bot.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;All it does is take a board, gets the legal moves it could make and picks one at random.&lt;/p&gt;

&lt;p&gt;Lets create a runner class to pit two random bots against each other and see how they perform.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;If we simulate 1000 games here are the results:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;x wins 577 times&lt;/li&gt;
&lt;li&gt;o wins 312 times&lt;/li&gt;
&lt;li&gt;ties 111 times&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can run this multiple times and the percentages are in this ballpark. Even though both are playing randomly, the x win percentage is higher because x always goes first. X has a first turn advantage.&lt;/p&gt;

&lt;h2&gt;
  
  
  OneLayer Bot
&lt;/h2&gt;

&lt;p&gt;A random strategy is really bad. Lets make our bot a little smarter. Our next bot looks at the current board, if there is a winning move it will pick it. Otherwise it will default to the random strategy.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The comments describe what our bot is doing. We’re basically performing a one layer search, hence the bot name. Our bot can look one move into the future and pick the best move if it is a win.&lt;/p&gt;

&lt;p&gt;Lets create another runner to test our bot, we’ll bit it against the randombot to see whether it improves or reduces winning percentages.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;We play 1000 games in each combination of bots. Not surprisingly our onelayerbot improves our odds of winning.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;randombot (x) vs. onelayerbot (o)

&lt;ul&gt;
&lt;li&gt;x wins: 390&lt;/li&gt;
&lt;li&gt;o wins: 529&lt;/li&gt;
&lt;li&gt;ties: 81&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;onelayerbot (x) vs randombot (o)

&lt;ul&gt;
&lt;li&gt;x wins: 805&lt;/li&gt;
&lt;li&gt;o wins: 109&lt;/li&gt;
&lt;li&gt;ties: 86&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;onelayerbot (x) vs onelayerbot (o)

&lt;ul&gt;
&lt;li&gt;x wins: 689&lt;/li&gt;
&lt;li&gt;o wins: 266&lt;/li&gt;
&lt;li&gt;ties: 45&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The first set of results is interesting, our one layer bot is able to reverse the first turn advantage that x has because it has a (marginally) better strategy.&lt;/p&gt;

&lt;h2&gt;
  
  
  TwoLayer Bot
&lt;/h2&gt;

&lt;p&gt;Lets build another bot that looks two moves into the future. It still picks a winning move if there is one, but it now blocks a winning move for the opponent.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Lines 21-29 are the new bit. It calculates determines if its opponent can win on it’s next turn. Playing in that space to prevent them from winning.&lt;/p&gt;

&lt;p&gt;Again lets create another runner to pit our bots against each other.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;randombot (x) vs twolayerbot (o)

&lt;ul&gt;
&lt;li&gt;x wins: 50&lt;/li&gt;
&lt;li&gt;o wins: 713&lt;/li&gt;
&lt;li&gt;ties: 237&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;twolayerbot (x) vs randombot (o)

&lt;ul&gt;
&lt;li&gt;x wins: 879&lt;/li&gt;
&lt;li&gt;o wins: 13&lt;/li&gt;
&lt;li&gt;ties: 108&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;twolayerbot (x) vs twolayerbot (o)

&lt;ul&gt;
&lt;li&gt;x wins: 310&lt;/li&gt;
&lt;li&gt;o wins: 164&lt;/li&gt;
&lt;li&gt;ties: 526&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Winning percentages continue to go up for our new bot against the random bot. You’ll also notice that when our twolayerbot plays against itself, it ties over half the games. it’s defense is a lot better.&lt;/p&gt;

&lt;h2&gt;
  
  
  InvinciBot
&lt;/h2&gt;

&lt;p&gt;And lastly, for the moment we’ve all been waiting for, a bot that will never lose a game of tic tac toe.&lt;/p&gt;

&lt;p&gt;InvinciBot!!!! 👍👏&lt;/p&gt;

&lt;p&gt;How does our bot do it? It implements a minimax search algorithm to calculate every possible combination of move. Therefore, ensuring with precision, to never make a move that would result in a loss.&lt;/p&gt;

&lt;p&gt;Because tic tac toe is a rather simple game, if both players always choose the an optimal strategy the game will always result in a tie. Which is why I say our bot will never lose, instead of saying it will always win. If it’s playing against an inferior opponent it will win most of the time!&lt;/p&gt;

&lt;p&gt;Our minimax implementation is a recursive depth first search algorithm. For a particular board, it calculates whether each move would result in a win, tie or lose.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Because it simulates every possible move, this bot takes a lot longer to play. Running locally, it takes about 30 secs to make the first move.&lt;/p&gt;

&lt;p&gt;Lets put together a runner to test out our bot (this runner took 25 minutes to run locally).&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;invincibot (x) vs randombot (o)

&lt;ul&gt;
&lt;li&gt;x wins: 15&lt;/li&gt;
&lt;li&gt;o wins: 0&lt;/li&gt;
&lt;li&gt;ties: 0&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;randombot (x) vs invincibot (o)

&lt;ul&gt;
&lt;li&gt;x wins: 0&lt;/li&gt;
&lt;li&gt;o wins: 13&lt;/li&gt;
&lt;li&gt;ties: 2&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;invincibot (x) vs invincibot (o)

&lt;ul&gt;
&lt;li&gt;x wins: 0&lt;/li&gt;
&lt;li&gt;o wins: 0&lt;/li&gt;
&lt;li&gt;ties: 15&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;InvinciBot dominates randombot. It’s not even close. And when invincibots play against each other, the game always ends in a tie. That is the optimal results for a game of tic tac toe. If each player using the best strategy, the game will always tie.&lt;/p&gt;

&lt;h2&gt;
  
  
  How InvinciBot Plays
&lt;/h2&gt;

&lt;p&gt;I’ll touch briefly on how InvinciBot is so good at tic tac toe. As mentioned before, it’s good (and takes so long) because it uses minimax to search through each possible move.&lt;/p&gt;

&lt;p&gt;Here is what a sample search would look like. It generates every possible combination for each player.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--V0MwaJiU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/e8yv2i60992sn45giv23.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--V0MwaJiU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/e8yv2i60992sn45giv23.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I left off most of the board states because I can’t draw that many. But the search doesn’t stop until a particular board ends with a win or a tie. Here’s the number of boards that are generated to pick each move in the game.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;1: 294,778&lt;/li&gt;
&lt;li&gt;2: 31,973&lt;/li&gt;
&lt;li&gt;3: 3,864&lt;/li&gt;
&lt;li&gt;4: 478&lt;/li&gt;
&lt;li&gt;5: 104&lt;/li&gt;
&lt;li&gt;6: 26&lt;/li&gt;
&lt;li&gt;7: 8&lt;/li&gt;
&lt;li&gt;8: 3&lt;/li&gt;
&lt;li&gt;9: 1&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To make the 1st move, InvinciBot generates over a quarter of a million potential boards. To make the 9th and last move, there’s only one open spot, so it only generates one board.&lt;/p&gt;

&lt;p&gt;As it generates possible board states, it remembers whenever a game ends in a win, tie or lose. Then at each level compares the best outcome for that particular board, ensuring that the player makes the best possible move.&lt;/p&gt;

&lt;p&gt;This strategy works well for simple games, but breaks down quickly in more complex games.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Thoughts
&lt;/h2&gt;

&lt;p&gt;I really enjoyed making these tic tac toe playing bots! It was fun to see a bot play tic tac toe. While the game is simple, we can still learn a lot of strategies to help us beat other games.&lt;/p&gt;

&lt;p&gt;There’s definitely a lot of room for optimization, alpha beta pruning being the logical optimization to make.&lt;/p&gt;

&lt;p&gt;If you’re interested in learning more about game playing bots, &lt;a href="https://twitter.com/mokenyon"&gt;follow me on twitter&lt;/a&gt;, I’ll be learning, writing and tweeting about it as I do it.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;I’m currently reading &lt;a href="https://www.manning.com/books/deep-learning-and-the-game-of-go"&gt;Deep Learning and the Game of Go&lt;/a&gt;, this post is inspired by my reading there. Specifically player and printing the board are inspired by that book. I would recommend the book to anyone looking for an in depth introduction to game playing bots.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Please see my &lt;a href="https://github.com/morgankenyon/RandomML/tree/master/src/tictactoe"&gt;github repo&lt;/a&gt; for full source code.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://thesharperdev.com/coding-the-perfect-tic-tac-toe-bot/"&gt;thesharperdev.com&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>machinelearning</category>
    </item>
    <item>
      <title>Implementing Minimax Tree Search</title>
      <dc:creator>Morgan Kenyon</dc:creator>
      <pubDate>Sun, 26 Apr 2020 00:54:48 +0000</pubDate>
      <link>https://forem.com/mokenyon/implementing-minimax-tree-search-1bjm</link>
      <guid>https://forem.com/mokenyon/implementing-minimax-tree-search-1bjm</guid>
      <description>&lt;p&gt;Game playing is one way to learn machine learning strategies. A most game playing bots involve some searching mechanism. It’s how the bot can “see” which move can result in a favorable outcome down the line.&lt;/p&gt;

&lt;p&gt;Lets learn about minimax, a useful technique to build an AI to compete on simple games.&lt;/p&gt;

&lt;h2&gt;
  
  
  Single Player Tree Searching
&lt;/h2&gt;

&lt;p&gt;Lets play a little game. The object of the game is to end up with the highest number.&lt;/p&gt;

&lt;p&gt;For a single turn, one player game the choice is simple.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--t_NaQPTQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/g4y4xsoxfwwqveztatfo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--t_NaQPTQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/g4y4xsoxfwwqveztatfo.png" alt="Single Turn Game"&gt;&lt;/a&gt;&lt;br&gt;
You go right, end of with a score of 10! That’s the highest possible score in our little game.&lt;/p&gt;

&lt;p&gt;Lets make it a little more complicated. Our game now has two turns, what do you choose?&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--wlm1Xcp1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/bzcb2mdvx3wcbvjxs50y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--wlm1Xcp1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/bzcb2mdvx3wcbvjxs50y.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;br&gt;
On your first turn, if you make the same decision (pick 10), that will leave you with bad options on your second turn (2 or 3).&lt;/p&gt;

&lt;p&gt;To achieve the highest score, you need to pick 1 on your first turn in order to be able to pick 20 on your second turn.&lt;/p&gt;

&lt;p&gt;One way to model this, is to start at the bottom and choose the max at each node. If we do that across our entire tree, we determine our max score (20) and which decisions to make (left, left).&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--2HuGyafJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/nzmcon4xr805jtj9uk8h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2HuGyafJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/nzmcon4xr805jtj9uk8h.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Two Player Tree Searching (Minimax)
&lt;/h2&gt;

&lt;p&gt;What if we introduced another player into this game? Now two players are competing to against each other. With a small tweak in the rules.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Player 1 wins if a positive number is chosen.&lt;/li&gt;
&lt;li&gt;Player 2 wins if a negative number is chosen.&lt;/li&gt;
&lt;li&gt;A tie occurs if 0 is chosen.&lt;/li&gt;
&lt;li&gt;Players alternate turns with Player 1 going first.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Lets take the following game.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--sok_76eC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/x3n9p8liibugdjp3b5wh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--sok_76eC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/x3n9p8liibugdjp3b5wh.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;br&gt;
Player 1 (P1) makes the first choice, then Player 2 (P2) has a turn, and finally Player 1 makes the final pick.&lt;/p&gt;

&lt;p&gt;Player 1 wants positive numbers, so they’re looking to maximize their score.&lt;/p&gt;

&lt;p&gt;Player 2 wants negative numbers, so they’re looking to minimize their score.&lt;/p&gt;

&lt;p&gt;That’s where the term minimax comes from, from players wanting to either minimize or maximize their score.&lt;/p&gt;

&lt;p&gt;How could this game play out? If each player choose the best available option to them at the time, the optimal game outcome is 7, which means Player 1 wins!&lt;/p&gt;

&lt;p&gt;Lets model this game as well.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--BzcsmZMd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/kb27tpmqo5c681mveomq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--BzcsmZMd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/kb27tpmqo5c681mveomq.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Again, Player 1 attempts to maximize their score, Player 2 attempts to minimize their score.&lt;/p&gt;

&lt;p&gt;Player 1 goes left, Player 2 goes left, and finally Player 1 goes right landing on a score of 7.&lt;/p&gt;
&lt;h2&gt;
  
  
  Programming Minimax
&lt;/h2&gt;

&lt;p&gt;Lets implement a minimax search in python!&lt;/p&gt;

&lt;p&gt;We first need a data structure to hold our values.&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;We create a &lt;code&gt;Node&lt;/code&gt; class, it can hold a single value and links to a left and right &lt;code&gt;Node&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Then we’ll create a &lt;code&gt;Choice&lt;/code&gt; class that represents the players choice.&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
&lt;br&gt;
Next we’ll initialize a tree with the values from the two player game we modeled above.


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
&lt;br&gt;
You’ll notice on line 41, I’m printing the tree. Which outputs the following:&lt;br&gt;
&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6YpRilTW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/sy65snhc3yrhjjmw4exk.png" alt="Alt Text"&gt;&lt;br&gt;
&lt;em&gt;The &lt;code&gt;print_tree&lt;/code&gt; function is available on the &lt;a href="https://github.com/morgankenyon/RandomML/blob/master/src/minimax.py#L15"&gt;github repo&lt;/a&gt;.&lt;/em&gt;

&lt;p&gt;We’ll solve this by coding a recursive depth first search algorithm. The main concerns we want to keep in mind are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;We need to keep track of which players turn it is, I’m using the is_max to track that.&lt;/li&gt;
&lt;li&gt;We need to know when to stop our search, in recursion that means we need some base cases.&lt;/li&gt;
&lt;li&gt;We want to explore our whole tree.
We need some comparison logic to determine which sub tree we will choose to explore.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Our base case will be when our node no longer has any children, we just return the value of the node.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;In order to explore our whole tree, we’ll call &lt;code&gt;minimax&lt;/code&gt; on each sub tree in our node.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Making sure to reverse &lt;code&gt;is_max&lt;/code&gt; because the players alternate turns.&lt;/p&gt;

&lt;p&gt;Finally, we compare the results. If we’re maximizing we take the max results, then if we’re minimizing we take the minimum results.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Lets create a little simulator to play our game for us.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Running this outputs the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Moving left to node with value -2&lt;/li&gt;
&lt;li&gt;Moving left to node with value 3&lt;/li&gt;
&lt;li&gt;Moving right to node with value 7&lt;/li&gt;
&lt;li&gt;Game ends with a score of 7&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Congrats! We’ve correctly demonstrated how to use minimax to optimally solve a simple two player game.&lt;/p&gt;

&lt;h2&gt;
  
  
  Parting Thoughts
&lt;/h2&gt;

&lt;p&gt;This game is about as simple as it gets. But searching is an integral part to most automated game playing bots. It’s how bots can “see” into the future.&lt;/p&gt;

&lt;p&gt;For a challenge, see if you can use minimax to build a tic tac toe playing bot.&lt;/p&gt;

&lt;p&gt;As you can imagine, with complicated games (Chess and Go) searching has its limitations due time and memory constraints. Further strategies such as alpha-beta prune and Monte Carlo simulation can help in those cases.&lt;/p&gt;

&lt;p&gt;You might have noticed that my base case will only work with nodes that have two or 0 child nodes. The minimax in the &lt;a href="https://github.com/morgankenyon/RandomML/blob/master/src/minimax.py"&gt;git repo&lt;/a&gt; will contain code to handle that condition.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://thesharperdev.com/implementing-minimax-tree-search/"&gt;thesharperdev.com&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>machinelearning</category>
    </item>
    <item>
      <title>Functional Fundamentals: Currying</title>
      <dc:creator>Morgan Kenyon</dc:creator>
      <pubDate>Sat, 30 Nov 2019 20:05:56 +0000</pubDate>
      <link>https://forem.com/mokenyon/functional-fundamentals-currying-3lm6</link>
      <guid>https://forem.com/mokenyon/functional-fundamentals-currying-3lm6</guid>
      <description>&lt;p&gt;Some time ago, I watched a talk that &lt;a href="https://twitter.com/ScottWlaschin?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor"&gt;Scott Wlaschin&lt;/a&gt; gave at a conference about functional programming. He said often times people who don’t understand functional programming get scared off by the &lt;a href="https://github.com/hemanth/functional-programming-jargon"&gt;terminology&lt;/a&gt;. Terms such as currying, partial application, functor, monad, etc.&lt;/p&gt;

&lt;p&gt;It’s easy to think these are super complex concepts, when in reality these terms are just unfamiliar.&lt;/p&gt;

&lt;p&gt;Object oriented programming has similar terminology, encapsulation, polymorphism, inheritance, etc. We’ve just been exposed to those terms so they’ve lost their scariness.&lt;/p&gt;

&lt;p&gt;Today lets dive into the topic at hand, currying.&lt;/p&gt;

&lt;h2&gt;
  
  
  Method Parameters in OO Land
&lt;/h2&gt;

&lt;p&gt;In most OO style programming languages, C#, Java, Python, C/C++, etc. A method has a set number of parameters.&lt;/p&gt;

&lt;p&gt;Take this C# method for concating strings.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;It takes two strings as input, and returns one string.&lt;/p&gt;

&lt;p&gt;Every time you call this method you must provide two parameters. If you don’t, the C# compiler complains.&lt;/p&gt;

&lt;h2&gt;
  
  
  Function Parameters in Functional Land
&lt;/h2&gt;

&lt;p&gt;On the other hand, in most functional style programming languages, F#, Elm, Haskell, etc. Function parameters are defined and leveraged differently.&lt;/p&gt;

&lt;p&gt;Here is how we define a function in Elm that needs two strings as input before it can return the output string.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Notice in Elm the definition of the function is on a separate line than the implementation. A lot of functional languages are like that.&lt;/p&gt;

&lt;p&gt;Also notice how the definition is in a different format, “string -&amp;gt; string -&amp;gt; string”. If you’ve never been exposed to a functional language before that might be a bit odd.&lt;/p&gt;

&lt;p&gt;Defining a similar function in F# is a bit different.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;But the signature is the same, here’s a screenshot of this function in VS Code using the the Ionide plugin.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6ys4Z0kZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i0.wp.com/thesharperdev.com/wp-content/uploads/2019/11/image-4.png%3Fw%3D586%26ssl%3D1" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6ys4Z0kZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i0.wp.com/thesharperdev.com/wp-content/uploads/2019/11/image-4.png%3Fw%3D586%26ssl%3D1" alt="F#"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Ionide adds the (// string -&amp;gt; string -&amp;gt; string) function definition automatically, you’ll notice it’s the same as Elm’s.&lt;/p&gt;

&lt;p&gt;Even though this take two strings as input, I can only give it one and the compiler doesn’t have any problem with it.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The signature of concateWordWith is now “string -&amp;gt; string”.&lt;/p&gt;

&lt;p&gt;Or I can it two parameters but in two sets of parenthesis.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Why is that?&lt;/p&gt;

&lt;p&gt;The reason is because of currying.&lt;/p&gt;

&lt;h2&gt;
  
  
  Currying Explained
&lt;/h2&gt;

&lt;p&gt;Currying is a fundamentally different way of handling functional parameters. In OO languages, it’s all or nothing. If a method has 3 inputs, give me 3 inputs or boom! Compile error.&lt;/p&gt;

&lt;p&gt;Curried functions offer more flexibility. They let you build up the input parameters over time. You can give one input now. Then later give it another input. Then finally the last one right before it’s used.&lt;/p&gt;

&lt;p&gt;Said another way, If a function has 3 inputs and you only give it one, it will return a function that takes 2 inputs. Then you can give that 2 input function one input and it will return a function that takes 1 input. Then you can give that 1 input function one input and it will finally return the output.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;So if you see a function that has a signature of “string -&amp;gt; string -&amp;gt; string”, an OO way to describe it would be “a function that takes two strings as input and returns one string as output”. A more functional way of describing would be “a function that takes a string, that returns an intermediate function that takes a string that returns a string.&lt;/p&gt;

&lt;p&gt;Because of currying, there’s really no such thing as a multi parameter function in most functional programming languages. If you’re passing multiple parameters, they’re really being applied one at a time to a sequence of intermediate functions. The compiler does this for you automatically.&lt;/p&gt;

&lt;p&gt;In fact &lt;a href="https://en.wikipedia.org/wiki/Currying"&gt;Wikipedia&lt;/a&gt; defines currying as “…the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument”. So breaking every argument down into it’s own separate function.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why is Currying Useful
&lt;/h2&gt;

&lt;p&gt;So now that you know what currying is, the next logical question is “is it useful”? Is this just one of those “functional” things that only exist to make life more complicated.&lt;/p&gt;

&lt;p&gt;In languages that support currying, currying provides a lot of flexibility with how you call functions.&lt;/p&gt;

&lt;p&gt;Take the following example in C# that adds 2 to every number in a list.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Pretty simple code. Here’s how you could do it in F# without taking advantage of currying*.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Fairly straight forward. But since F# curries functions, here’s a more functional way of doing it.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The add function takes two inputs, but in this example we give it one input (2). Then let the List.map provide the second input, one for each element of the list.&lt;/p&gt;

&lt;p&gt;Granted, that isn’t a world changing difference. In my day job I write C#, so I deal with non-curried functions all the time. But if you spend enough time in a curried language you begin to miss the little shortcuts and niceties.&lt;/p&gt;

&lt;p&gt;*Yes, every function is automatically curried, so not technically a true statement. But different from the next example.&lt;/p&gt;

&lt;h2&gt;
  
  
  Wrapping Up
&lt;/h2&gt;

&lt;p&gt;Currying is an important concept to know when working in functional languages. It’s a great language feature that comes in handy all over the place.&lt;/p&gt;

&lt;p&gt;Currying is just one of many concepts that I was never exposed to in the OO world. I hope you take some time to learn functional programming and all the unique features it has to offer.&lt;/p&gt;

&lt;p&gt;Sources&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Currying"&gt;https://en.wikipedia.org/wiki/Currying&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://softwareengineering.stackexchange.com/questions/185585/what-is-the-advantage-of-currying"&gt;https://softwareengineering.stackexchange.com/questions/185585/what-is-the-advantage-of-currying&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.quora.com/What-are-the-advantages-of-currying-in-functional-programming"&gt;https://www.quora.com/What-are-the-advantages-of-currying-in-functional-programming&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>functional</category>
    </item>
    <item>
      <title>How to Write a Brainfuck Interpreter in C#</title>
      <dc:creator>Morgan Kenyon</dc:creator>
      <pubDate>Sun, 13 Oct 2019 16:16:17 +0000</pubDate>
      <link>https://forem.com/mokenyon/how-to-write-a-brainfuck-interpreter-in-c-3olb</link>
      <guid>https://forem.com/mokenyon/how-to-write-a-brainfuck-interpreter-in-c-3olb</guid>
      <description>&lt;p&gt;I’ve always been somewhat interested in how programming languages are written. Last month I bought &lt;a href="https://interpreterbook.com/"&gt;Writing An Interpreter In Go&lt;/a&gt;, and am about 40% of the way through that book (though my version is in C#). I’ve hand built a tokenizer and am starting to write my own parser.&lt;/p&gt;

&lt;p&gt;It’s gotten me curious about programming languages, and I wanted to try my hand at building a brainfuck interpreter. Lets dive in.&lt;/p&gt;

&lt;h1&gt;
  
  
  Brainfuck
&lt;/h1&gt;

&lt;p&gt;&lt;a href="https://en.wikipedia.org/wiki/Brainfuck"&gt;Brainfuck&lt;/a&gt; is an &lt;a href="https://en.wikipedia.org/wiki/Esoteric_programming_language"&gt;esoteric programming langauge&lt;/a&gt;. It’s designed to be confusing, hence the name. The language only consists of 8 characters, &lt;code&gt;&amp;gt;&lt;/code&gt; &lt;code&gt;&amp;lt;&lt;/code&gt; &lt;code&gt;+&lt;/code&gt; &lt;code&gt;-&lt;/code&gt; &lt;code&gt;.&lt;/code&gt; &lt;code&gt;,&lt;/code&gt; &lt;code&gt;[&lt;/code&gt; &lt;code&gt;]&lt;/code&gt;. With an internal structure defined by &lt;a href="https://en.wikipedia.org/wiki/Brainfuck#Language_design"&gt;wikipedia&lt;/a&gt; as:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The brainfuck language uses a simple machine model consisting of the program and instruction pointer, as well as an array of at least 30,000 byte cells initialized to zero; a movable data pointer (initialized to point to the leftmost byte of the array); and two streams of bytes for input and output (most often connected to a keyboard and a monitor respectively, and using the ASCII character encoding).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Each character in the language is defined as:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&amp;lt;&lt;/code&gt; : increment the data pointer (to point to the next cell to the right)&lt;br&gt;
&lt;code&gt;&amp;gt;&lt;/code&gt; : decrement the data pointer (to point to the next cell to the left)&lt;br&gt;
&lt;code&gt;+&lt;/code&gt; : increment (increase by one) the byte at the data pointer &lt;br&gt;
&lt;code&gt;-&lt;/code&gt; : decrement (decrease by one) the byte at the data pointer. &lt;br&gt;
&lt;code&gt;.&lt;/code&gt; : output the byte at the data pointer&lt;br&gt;
&lt;code&gt;,&lt;/code&gt; : accept on byte of input, storing its value in the byte at the data pointer&lt;br&gt;
&lt;code&gt;[&lt;/code&gt; : if the byte at the data pointer is zero, then instead of moving the instruction pointer forward to the next command, jump it forward to the command after the matching ] command.&lt;br&gt;
&lt;code&gt;]&lt;/code&gt; : if the byte at the data pointer is nonzero, then instead of moving the instruction pointer forward to the next command, jump it back to the command after the matching [ command. &lt;/p&gt;

&lt;p&gt;Here is a program that prints out “Hello World”:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;If this is your first esoteric programming language, this definitely throws you for a loop. Since this article is about documenting how to build an interpreter, here’s a &lt;a href="https://www.youtube.com/watch?v=-3C200nCwpk"&gt;great video&lt;/a&gt; describing brainfuck to anyone to wants a more visual representation.&lt;/p&gt;

&lt;p&gt;So lets see some basic code examples.&lt;/p&gt;

&lt;h1&gt;
  
  
  Examples
&lt;/h1&gt;

&lt;p&gt;If I wanted to write a single exclamation point, here is a program that would do that:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;It uses the &lt;code&gt;+&lt;/code&gt; character to add 1 to the current data pointer 33 times, 33 being the ASCII representation for an exclamation point. Then uses the &lt;code&gt;.&lt;/code&gt; character to print that single character.&lt;/p&gt;

&lt;p&gt;Here are three different programs that print out &lt;code&gt;!?&lt;/code&gt;:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The first version generates and prints the exclamation pointer as before, then moves to the next cell and increments data pointer to 63, the ASCII representation for ?, and then prints it.&lt;/p&gt;

&lt;p&gt;The second version reuses the cell of the exclamation mark, so it only needs to increment that cell 30 more times. 33 (!) + 30 = 63 (?)&lt;/p&gt;

&lt;p&gt;The third version uses the &lt;code&gt;[&lt;/code&gt; and &lt;code&gt;]&lt;/code&gt; brackets to repeat sections of code resulting in smaller programs.&lt;/p&gt;

&lt;h1&gt;
  
  
  The Interpreter
&lt;/h1&gt;

&lt;p&gt;I’ve named my interpreter &lt;a href="https://github.com/MorganW09/Dizzy"&gt;Dizzy&lt;/a&gt;, because programming in brainfuck can make you dizzy.&lt;/p&gt;

&lt;p&gt;Well that aside, there’s not a whole lot of complexity to the interpreter.&lt;/p&gt;

&lt;p&gt;Lets start off by creating a class called &lt;code&gt;Interpreter&lt;/code&gt; that will be interpreting our program.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;It has three instance variables: 1. A byte array to hold any data we might need, 2. A pointer telling us where we are in that array, 3. The input converted into a char array.&lt;/p&gt;

&lt;p&gt;Then lets create a scaffold of our Run method, which is a switch statement for each of the 8 valid characters in our language.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;em&gt;In brainfuck, any other characters are just ignored, so anything not in this set of 8 will just be skipped over.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Given our definition above, for &lt;code&gt;&amp;gt;&lt;/code&gt; and &lt;code&gt;&amp;lt;&lt;/code&gt;, we need to increment and decrement the pointer.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Then for &lt;code&gt;+&lt;/code&gt; and &lt;code&gt;-&lt;/code&gt;, we need to increment and decrement the current value in our tape referenced by the pointer.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Then our IO characters are also pretty simple:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Finally we need to implement our brackets. Brackets help us repeat or skip sections of a brainfuck program, kind of like a goto statement. That’s why the third program for writing !? was so much shorter, brackets allowed the same section code to be run multiple times.&lt;/p&gt;

&lt;p&gt;The only complication here is nested brackets. For a program like &lt;code&gt;[+[+]+]&amp;gt;+&lt;/code&gt;, which skips from the first open bracket to the last close bracket, we need to keep track which open/close brackets belong together.&lt;/p&gt;

&lt;p&gt;We introduce an int called &lt;code&gt;unmatchedBracketCounter&lt;/code&gt;, (defined outside the for loop) which tracks how many pairs of brackets we’ve encountered. If we’re looking for a &lt;code&gt;]&lt;/code&gt; and encounter another &lt;code&gt;[&lt;/code&gt;, we know we will have to now pass two &lt;code&gt;]&lt;/code&gt; before we can stop.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Combining all these elements we end up with a single class that can interpret a brainfuck program.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h1&gt;
  
  
  Testing
&lt;/h1&gt;

&lt;p&gt;Now for testing. As someone who codes for a living, I feel very comfortable writing programs in normal programming languages. Brainfuck programs are another matter.&lt;/p&gt;

&lt;p&gt;Fortunately I found this &lt;a href="https://copy.sh/brainfuck/"&gt;great website&lt;/a&gt; which has brainfuck programs, can run brainfuck programs, and can generate brainfuck programs as well.&lt;/p&gt;

&lt;p&gt;Here are some fun programs that I found on that website.&lt;/p&gt;

&lt;h2&gt;
  
  
  CALCULATE PI
&lt;/h2&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;This calculates Pi to the 15 decimal place. When run the output is &lt;code&gt;3.14070455282885&lt;/code&gt;, which the first 15 digits of PI are &lt;code&gt;3.14159265358979&lt;/code&gt;, which I am using an 8 bit cell, so it seems like I’m experiencing some overflows as called out in the program.&lt;/p&gt;

&lt;h2&gt;
  
  
  CALCULATE SQUARES
&lt;/h2&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;When run this programs outputs all squares up to 10000, 0, 1, 4, 9 16, …, 9801, 1000.&lt;/p&gt;

&lt;h2&gt;
  
  
  99 BOTTLES OF BEER
&lt;/h2&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;When run this prints out the 99 bottles of beer chanty, from 99 all the way to 0.&lt;/p&gt;

&lt;h2&gt;
  
  
  PRINT ONE ENTERED CHARACTER
&lt;/h2&gt;

&lt;p&gt;And finally a program that takes advantage of user input. Most brainfuck programs that I found didn’t use the input character ,, I wrote one with the help of the text generator mentioned earlier.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h1&gt;
  
  
  Closing Thoughts
&lt;/h1&gt;

&lt;p&gt;There you have it. A interpreter that will run brainfuck programs.&lt;/p&gt;

&lt;p&gt;I definitely enjoyed writing this interpreter. The first one that I’ve written from scratch. It was a fun and pretty different programming challenge from what I’m used to.&lt;/p&gt;

&lt;p&gt;I hope you enjoyed it and continue to experiment with things that you’re interested in.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://thesharperdev.com/how-to-write-a-brainfuck-interpreter-in-c/"&gt;thesharperdev.com&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>csharp</category>
    </item>
    <item>
      <title>C# Design Patterns: The Visitor Pattern</title>
      <dc:creator>Morgan Kenyon</dc:creator>
      <pubDate>Sun, 29 Sep 2019 10:35:04 +0000</pubDate>
      <link>https://forem.com/mokenyon/c-design-patterns-the-visitor-pattern-48e4</link>
      <guid>https://forem.com/mokenyon/c-design-patterns-the-visitor-pattern-48e4</guid>
      <description>&lt;p&gt;My &lt;a href="https://thesharperdev.com/an-introduction-to-c-expression-trees/"&gt;last article&lt;/a&gt; introduced expressions in C# and explained a bit why they were useful. Today I’m going to build upon that article and introduce you to the Visitor Pattern, a common pattern used when dealing with expressions. If you’re not familiar with expressions or a bit rusty, I would recommend reading the previous article first.&lt;/p&gt;

&lt;h1&gt;
  
  
  The Visitor Pattern
&lt;/h1&gt;

&lt;p&gt;&lt;a href="https://en.wikipedia.org/wiki/Visitor_pattern"&gt;Wikipedia&lt;/a&gt; defines the visitor pattern as "the visitor design pattern is a way of separating an algorithm from an object structure on which it operates".&lt;/p&gt;

&lt;p&gt;What does that mean? When I normally define classes in C#, they look something like this.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Inside of my class, I’m defining my data and my methods or algorithms that operate on my class.&lt;/p&gt;

&lt;p&gt;But if you’re using the Visitor Pattern, you break apart the class and the methods into something like this.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Now the data and the methods are defined separately, decoupling them has advantages which we’ll see in a moment.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;As a note, breaking apart the data and methods in this example really doesn’t do anything for you, also I’m not using the Visitor Pattern terminology, but we’ll explore that next.&lt;/em&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Printing Expressions
&lt;/h1&gt;

&lt;p&gt;&lt;em&gt;The code that follows builds upon the example shown in this &lt;a href="https://en.wikipedia.org/wiki/Visitor_pattern#C#_example"&gt;Wikipedia article&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Lets demo this pattern by defining expressions to represent simple mathematical equations and a visitor to print out our equations.&lt;/p&gt;

&lt;p&gt;To start with our pattern, I’m going to define two interfaces. &lt;code&gt;IExpressionVisitor&lt;/code&gt; defines what types of expressions our visitor supports. Anything inheriting from &lt;code&gt;IExpression&lt;/code&gt; are the objects that are going to be “visited”. The Accept method is the standard name for the method that allows the visitor to be accepted into the &lt;code&gt;IExpression&lt;/code&gt; class.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Next lets define our first expression called &lt;code&gt;Literal&lt;/code&gt;. It’s responsibility is to hold the number values in our equations.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;You’ll notice that it inherits from &lt;code&gt;IExpression&lt;/code&gt;, and implements the Accept method, all it does it pass itself into the visitor by the &lt;code&gt;this&lt;/code&gt; keyword.&lt;/p&gt;

&lt;p&gt;Next I’ll need a &lt;code&gt;Addition&lt;/code&gt; expression defined as follows.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;I’m defining two &lt;code&gt;IExpressions&lt;/code&gt;, Left and Right, to be the two expressions that will be added together.&lt;/p&gt;

&lt;p&gt;Now that I have two expressions, I’m going to need a visitor to be able to visit those expressions and print out the equation.&lt;/p&gt;

&lt;p&gt;Lets call our visitor &lt;code&gt;InfixExpressionPrinter&lt;/code&gt; and give it the following implementation.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;This has two methods for how to handle both of my expression types. If it’s a &lt;code&gt;Literal&lt;/code&gt;, all I need is to print the value. If it’s an &lt;code&gt;Addition&lt;/code&gt;, it generates the values of both the Left and Right expressions and adds them together.&lt;/p&gt;

&lt;p&gt;Now lets put that all together in order to print out our expression.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;I’m creating a simple &lt;code&gt;Addition&lt;/code&gt; equation, calling the Accept method visits the entire expression and prints the equation represented by our expression tree. Running this prints &lt;code&gt;(5+6)&lt;/code&gt;, which reflects the equation we built with expressions.&lt;/p&gt;

&lt;p&gt;We can also print out more complex expressions, such as the following.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Running this outputs &lt;code&gt;(((5+6)+20)+(1+3))&lt;/code&gt;, also the mathematical representation of our expression.&lt;/p&gt;

&lt;p&gt;The astute reader will notice that our expression printer prints equations in Infix notation. What if we wanted to print Prefix? Or Postfix?&lt;/p&gt;

&lt;p&gt;This is really the power of the Visitor Pattern. Since the logic for printing isn’t contained in our expression classes, we’re free to add another printer as long as we inherit from the &lt;code&gt;IExpressionVisitor&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;Lets define a printer for Prefix notation.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;When the second example is run using the second equation the result is &lt;code&gt;+ + + 5 6 20 + 1 3&lt;/code&gt;. Creating a new visitor allows us to convert the same expression into a different output.&lt;/p&gt;

&lt;h1&gt;
  
  
  Benefits of the Visitor Pattern
&lt;/h1&gt;

&lt;p&gt;As you can see in our examples, printing different forms of the equations doesn’t require any changes to our &lt;code&gt;Literal&lt;/code&gt; or &lt;code&gt;Addition&lt;/code&gt; classes. The Visitor Pattern allows some other class to define how to print expressions, and it hands off that responsibility to whoever implements the &lt;code&gt;IExpressionVisitor&lt;/code&gt; interface.&lt;/p&gt;

&lt;p&gt;This is a pretty trivial example of the Visitor Pattern. If you want to see an enterprise example of this pattern, look through the &lt;a href="https://github.com/aspnet/EntityFrameworkCore/tree/release/3.0"&gt;Entity Framework Core&lt;/a&gt; code base. It uses this pattern (and a lot more) to turn a Linq statement into a Database specific query.&lt;/p&gt;

&lt;p&gt;Instead of simple classes like &lt;code&gt;Literal&lt;/code&gt;, &lt;code&gt;Addition&lt;/code&gt;, &lt;code&gt;InfixExpressionPrinter&lt;/code&gt; and &lt;code&gt;PrefixExpressionPrinter&lt;/code&gt;, they have complex classes like &lt;a href="https://github.com/aspnet/EntityFrameworkCore/blob/release/3.0/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs"&gt;SelectExpression&lt;/a&gt;, &lt;a href="https://github.com/aspnet/EntityFrameworkCore/blob/release/3.0/src/EFCore.Relational/Query/SqlExpressions/ColumnExpression.cs"&gt;ColumnExpression&lt;/a&gt;, &lt;a href="https://github.com/aspnet/EntityFrameworkCore/blob/release/3.0/src/EFCore.Relational/Query/SqlExpressions/OrderingExpression.cs"&gt;OrderingExpression&lt;/a&gt; and &lt;a href="https://github.com/aspnet/EntityFrameworkCore/blob/release/3.0/src/EFCore.SqlServer/Query/Internal/SqlServerQuerySqlGenerator.cs"&gt;SqlServerQuerySqlGenerator&lt;/a&gt; which contains this method:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;That method looks pretty similar to the examples that we created in this article.&lt;/p&gt;

&lt;p&gt;Entire SQL projects are devoted to converting expressions into each particular data store. Whether that be SQL Server, Sqlite, Oracle, Postgres or others.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Entity Framework Core obviously has a lot of complexities to it, but like most other software, it’s built upon principles or patterns that most of us can familiarize ourselves. The Visitor Pattern happens to be one of those patterns.&lt;/em&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Closing Thoughts
&lt;/h1&gt;

&lt;p&gt;I’ve heard it said that design patterns are “experience reuse”. As an industry, we encounter very common problems across technologies and business domains. Patterns exist to solve those problems that have been born from both pains and successes in the past.&lt;/p&gt;

&lt;p&gt;Knowing Design Patterns helps us learn how to avoid making the same mistakes again. Design Patterns are great tools in the developer toolbox and I’m glad to have shared about one today.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published on &lt;a href="https://thesharperdev.com/c-design-patterns-the-visitor-pattern/"&gt;thesharperdev.com&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;a href="https://github.com/MorganW09/DesignPatterns"&gt;Github Library&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>design</category>
    </item>
    <item>
      <title>An Introduction to C# Expression Trees</title>
      <dc:creator>Morgan Kenyon</dc:creator>
      <pubDate>Mon, 23 Sep 2019 17:14:11 +0000</pubDate>
      <link>https://forem.com/mokenyon/an-introduction-to-c-expression-trees-1fh9</link>
      <guid>https://forem.com/mokenyon/an-introduction-to-c-expression-trees-1fh9</guid>
      <description>&lt;p&gt;&lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/"&gt;Expression Trees&lt;/a&gt; are an interesting C# language feature that you might not have knowingly used before. Expression Trees are fundamental to Entity Framework being able to turn C# code into SQL queries. So if you’ve ever used Entity Framework then you’ve definitely taken advantage of this language feature.&lt;/p&gt;

&lt;p&gt;For example, here is the &lt;a href="https://github.com/aspnet/EntityFrameworkCore/blob/release/3.0/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs"&gt;SelectExpression&lt;/a&gt; class in the Entity Framework Core (EF Core) library, searching for the term Expression shows that is exists 652 times in this class, pretty important!&lt;/p&gt;

&lt;p&gt;Lately I’ve been interested in how Entity Framework turns C# into SQL and wanted to write an article about Expressions to aid in my understanding of the subject.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;As a note, there is a difference between &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/"&gt;Expression Trees&lt;/a&gt; and &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expressions"&gt;Expressions&lt;/a&gt;, but across the internet and in software, such as Entity Framework, you’ll find both words used to describe Expression Trees. Which makes it a bit confusing and a little hard to google. I'll mainly be using the term Expressions for the remainder of this article.&lt;/em&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Why do we need Expressions?
&lt;/h1&gt;

&lt;p&gt;Most of the time, the code we write is intended to be executed in the exact place that we’re writing it.&lt;/p&gt;

&lt;p&gt;For example, this method is used to sum numbers.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Whenever this method is called with two numbers, it returns the sum. It always operates inside this method, inside of a C# runtime.&lt;/p&gt;

&lt;p&gt;What if I were to tell you that I needed you to write some piece of code that was intended to be run somewhere else? Like a database?&lt;/p&gt;

&lt;p&gt;You can’t pass code like this to a database (more realistically, some library that communicates with the database) and expect it to know what to do with it. You need a different way to represent code.&lt;/p&gt;

&lt;p&gt;That is what Expression Trees or Expressions are for.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as &lt;code&gt;x &amp;lt; y&lt;/code&gt;.&lt;/em&gt; ~&lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/"&gt;Microsoft Docs&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Expressions are a different format to describe code. They’re a data structure that represents code. They’re also “portable” in the sense that Expressions can be passed around and some other piece of code can investigate it to see what it’s suppose to do.&lt;/p&gt;

&lt;p&gt;Here’s an example of the earlier Sum method but now it’s in expression format.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;It performs the same functionality, adds two numbers, but it’s defined completely differently. That difference gives it it’s “portability”. The &lt;a href="https://en.wikipedia.org/wiki/Visitor_pattern#C#_example"&gt;visitor pattern&lt;/a&gt; is a common way to investigate an expression to figure out what it contains or means, which I hope to explore soon on this blog.&lt;/p&gt;

&lt;p&gt;Both parameters are defined by a ParameterExpression which denotes the type. Those parameters get passed into a BinaryExpression which adds them. Then all three of those Expressions are passed into a Lambda Expression which results in an &lt;code&gt;Expression&amp;lt;Func&amp;lt;int, int, int&amp;gt;&amp;gt;&lt;/code&gt;, which is a mouthful.&lt;/p&gt;

&lt;p&gt;Expressions can’t be called directly, so in order to use it we need to compile the Expression. Which turns it back into a regular Func which can then be called and the sum returned.&lt;/p&gt;

&lt;p&gt;I believe most anything that you can write as regular code can be written as an expression. I wouldn’t recommend it, but I believe it is possible.&lt;/p&gt;

&lt;h1&gt;
  
  
  Hello World Expression
&lt;/h1&gt;

&lt;p&gt;What would Hello World look like if it was written in Expressions? Something like this.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Lets go through this line by line.&lt;/p&gt;

&lt;p&gt;Line 3 defines our “Hello World” message as a constant of type string.&lt;/p&gt;

&lt;p&gt;Lines 5-7 defines the call to the method to print the message. The Expression.Call() method takes in two arguments,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Information about the method (line 6), which consists of: the type the method exists on (Console), the method name* (WriteLine), then what are the parameters we can pass to this method, (1 parameter with type string).&lt;/li&gt;
&lt;li&gt;The parameter (line 7).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Line 9 pushes that expression into a lambda expression.&lt;/p&gt;

&lt;p&gt;Line 11 compiles that expression into an Action.&lt;/p&gt;

&lt;p&gt;Line 13 runs the Action.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;You’ll notice that the name of the method is a string, so there’s no compiler checking for you on that.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;So that’s a Hello World example. Here are some examples of more expressions.&lt;/p&gt;

&lt;h2&gt;
  
  
  Print Message
&lt;/h2&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Instead of printing “Hello World”, this expression can now print any arbitrary string. The main difference is we’re defining a ParameterExpression instead of a ConstantExpression.&lt;/p&gt;

&lt;h2&gt;
  
  
  Print Number
&lt;/h2&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Now we’re printing any int. So we’ve updated some of our types and also combining defining our action expression and compiling it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Finding Max Number
&lt;/h2&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Here we are taking two ints and calling the Math.Max function. Notice that in this example we’re using a Func instead of an Action. Action is only defined for 0 or 1 parameters. Now that we have 2 parameters we have to use Func.&lt;/p&gt;

&lt;h2&gt;
  
  
  Calculate Slope
&lt;/h2&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;This one gets a bit more complicated, 4 parameters. It calculates the slope between two points on a line, (x1, y1) and (x2, y2), using the formula (y2-y1)/(x2-x1).&lt;/p&gt;

&lt;h2&gt;
  
  
  Extract Order Id
&lt;/h2&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Now instead of dealing with primitives we’re dealing with an Order object that has the property OrderId. Notice that we have to define a MemberExpression to extract a member of a type.&lt;/p&gt;

&lt;h2&gt;
  
  
  Sum Order Costs
&lt;/h2&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Then the last expression example for today, taking two Order objections and adding the cost for each one.&lt;/p&gt;

&lt;h1&gt;
  
  
  Final Thoughts
&lt;/h1&gt;

&lt;p&gt;At first building expressions by hand is odd. The expression version definitely takes a lot longer to define, but those extra steps helps an expression be more usable than a line of code that you would find in a normal C# program.&lt;/p&gt;

&lt;p&gt;I’m just getting my feet wet with Expressions and will continue to learn and blog about them here.&lt;/p&gt;

&lt;p&gt;If you have any questions or observations I’d love to hear about them in the comments below.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published on &lt;a href="https://thesharperdev.com/an-introduction-to-c-expression-trees/"&gt;thesharperdev.com&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Resources&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://github.com/MorganW09/ExpressionPlayground"&gt;Github Library&lt;/a&gt; containing these examples and more.&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/"&gt;https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://blogs.msdn.microsoft.com/charlie/2008/01/31/expression-tree-basics/"&gt;https://blogs.msdn.microsoft.com/charlie/2008/01/31/expression-tree-basics/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://weblogs.asp.net/dixin/functional-csharp-function-as-data-and-expression-tree"&gt;https://weblogs.asp.net/dixin/functional-csharp-function-as-data-and-expression-tree&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.tutorialsteacher.com/linq/expression-tree"&gt;https://www.tutorialsteacher.com/linq/expression-tree&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
    </item>
    <item>
      <title>An Introduction to Pure v. Impure Functions</title>
      <dc:creator>Morgan Kenyon</dc:creator>
      <pubDate>Wed, 11 Sep 2019 17:34:45 +0000</pubDate>
      <link>https://forem.com/mokenyon/an-introduction-to-pure-v-impure-functions-b47</link>
      <guid>https://forem.com/mokenyon/an-introduction-to-pure-v-impure-functions-b47</guid>
      <description>&lt;p&gt;Pure and Impure functions is a very important distinction in functional programming. Most of my university and early work experience was primarily in OOP languages (Java and C#) and I was never aware of this distinction.&lt;/p&gt;

&lt;p&gt;Today I wanted to introduce this concept and how it can help write more testable and composable software.&lt;/p&gt;

&lt;h1&gt;
  
  
  Function Types
&lt;/h1&gt;

&lt;p&gt;Any function is either pure or impure. &lt;a href="https://en.wikipedia.org/wiki/Pure_function"&gt;Wikipedia states&lt;/a&gt; that a pure function has the following two properties:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It’s return value is the same for the same arguments.&lt;/li&gt;
&lt;li&gt;It’s evaluation has no side effects.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So what exactly does that mean? Lets take the following function:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Given the same x and y, this function will always return the sum of those two ints. If x = 1 and y = 1, it will always return 2. If x = 100 and y = 100, it will always return 200. &lt;/p&gt;

&lt;p&gt;But this function:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The output of this function now depends on a third variable z, which is not one of the arguments. Since the function could return a different result for the same inputs it’s now an impure function. &lt;/p&gt;

&lt;p&gt;Or this next function:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The sum only depends on it’s inputs, which is good. There’s now a database call, which is a side effect. There’s also the possibility that the database operation can throw an exception. So the database call has introduced some complexity and side effects to our function. Which means it’s also an impure function.&lt;/p&gt;

&lt;h1&gt;
  
  
  The Testability of a Function
&lt;/h1&gt;

&lt;p&gt;Why is it important to know the distinction between types of functions? &lt;/p&gt;

&lt;p&gt;One big reason is that pure functions are inherently testable.&lt;/p&gt;

&lt;p&gt;Say I’m your manager, and I tasked you with verify that the following two method’s logic was correct.  &lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The AddPure method is almost trivial to test and verify that it’s working correctly.&lt;/p&gt;

&lt;p&gt;On the other hand the AddImpure method presents some challenges. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Where is z defined at? &lt;/li&gt;
&lt;li&gt;How can I initialize z?&lt;/li&gt;
&lt;li&gt;Do I have to create a class or classes to verify this method?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Testing the AddImpure method is doable, we now have to jump through some hoops because of it’s impureness. &lt;/p&gt;

&lt;p&gt;Or if we wanted to test the AddDb method. &lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;We’d now have to deal with a database call in the middle of our function. In an object oriented language, dependency injection is usually what we rely on in order to remove dependencies when we test. Dependency injection allows us to change what type of Db our method is using. If we’re testing, here’s a mock db, if we’re running our app, here’s the real database. &lt;/p&gt;

&lt;p&gt;In an object oriented language, that’s the recommended way to make functions testable. But that doesn’t mean it’s the only way to solve this problem.&lt;/p&gt;

&lt;h1&gt;
  
  
  A More Functional Approach
&lt;/h1&gt;

&lt;p&gt;Lets take a step back and break down our AddDb function. What are its responsibilities?&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Summing two numbers and returning the result&lt;/li&gt;
&lt;li&gt;Saving the result to a database&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Our function does two distinct things. When we are unit testing, what are we attempting to verify? Our unit test is only verifying that responsibility #1 is correct. We use dependency injection to avoid having to deal with responsibility #2.&lt;/p&gt;

&lt;p&gt;That begs the question, if we’re only testing half of what our function is doing, and introducing tools in order to avoid dealing with the other half, can we refactor this function?&lt;/p&gt;

&lt;p&gt;In languages that have functions as first class citizens, this is pretty easy to do. C# has the ability to define Functions, then pass those functions to methods. We could refactor our function into the following:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;So whatever operation we’ve decided to do, that is now being defined outside of our function.&lt;/p&gt;

&lt;p&gt;We’ve broken our single function into two functions. There are several great benefits from doing this.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The Sum function is now a pure function. &lt;/li&gt;
&lt;li&gt;I can now test my Sum logic without worrying about dealing with the database. &lt;/li&gt;
&lt;li&gt;I can also change the behavior of AddFunctional without modifying it. Which means we should rename the function to something more generic.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Because the AddFunctional takes in a function, any function that has the same signature can now be used in this method.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Suddenly my single method supports anything that can conform to the Func signature. Which helps the composability of my application.&lt;/p&gt;

&lt;h1&gt;
  
  
  Implications on Software Design and Architecture
&lt;/h1&gt;

&lt;p&gt;If this information is new to you, you might be thinking to yourself, “lets make everything pure!” Unfortunately most of the useful things that applications do require using impure functions.&lt;/p&gt;

&lt;p&gt;Things like saving and retrieving information to a database, making http requests, etc, those are all impure functions because they violate one or both of the conditions of pure functions.&lt;/p&gt;

&lt;p&gt;When writing your application, you should strive to maximize the number of pure methods used. If it’s possible, implement something using a pure method rather than an impure method. Or refactor a single impure method into smaller methods where some are pure, like our database example. &lt;/p&gt;

&lt;p&gt;Pure methods make your code easier to reason about and easier to test. Impure methods are usually always required, but knowing the distinction can lead to better software design.&lt;/p&gt;

&lt;h1&gt;
  
  
  Closing Thoughts
&lt;/h1&gt;

&lt;p&gt;Pure v. impure methods wasn’t something I was aware of until I started learning a functional programming language (F#). Even though I use C# in my day job, learning functional programming techniques has helped me write better software.&lt;/p&gt;

&lt;p&gt;In my next post I’ll expand a bit more on this topic. I’ll explain some of the implications and talk about what happens when we start chaining function calls together.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originallly published at &lt;a href="https://thesharperdev.com/pure-v-impure-functions/"&gt;theshaperdev.com&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>functional</category>
      <category>dotnet</category>
    </item>
    <item>
      <title>Benchmarking and Exploring C#'s Dynamic Keyword</title>
      <dc:creator>Morgan Kenyon</dc:creator>
      <pubDate>Mon, 26 Aug 2019 00:39:24 +0000</pubDate>
      <link>https://forem.com/mokenyon/benchmarking-and-exploring-c-s-dynamic-keyword-1l5i</link>
      <guid>https://forem.com/mokenyon/benchmarking-and-exploring-c-s-dynamic-keyword-1l5i</guid>
      <description>&lt;p&gt;Today I wanted to explore and benchmark a C# feature that I've never used before, the dynamic type. &lt;/p&gt;

&lt;h1&gt;
  
  
  Dynamic v. Static Type Systems
&lt;/h1&gt;

&lt;p&gt;A simple way to group programming languages is based on their type system. A statically typed language will enforce correct usage of types. Usually a compiler will check a types usage, and if you call a method that doesn't exist on a type or some other non allowable way, you'll get a compiler error. Think languages like C++, Java or C#. &lt;/p&gt;

&lt;p&gt;On the other hand, a dynamically typed language only checks types at runtime. So if you're incorrectly calling a method that doesn't exist on a class, you won't find out until your application is running. Think languages like JavaScript, Python, Ruby or PHP. &lt;/p&gt;

&lt;p&gt;We usually like to think of programming languages as being either dynamic or statically typed, and most languages push you towards one or the other. C# and Python are examples of languages that have the ability to do both. C# has a dynamic keyword that eliminates compile time checks and Python has recently introduced static type checking via &lt;a href="http://mypy-lang.org/" rel="noopener noreferrer"&gt;mypy&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;There are pros and cons to both type systems, I personally favor static typing. But C# gives you the freedom to use dynamic typing.&lt;/p&gt;

&lt;p&gt;In my 5 years of professional programming I haven't run into a case yet where I have needed to use the dynamic keyword. But sometimes using the dynamic keyword and bypassing the compiler is really the only feasible option. But they do exist, and to quote the Microsoft docs:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Therefore, you do not have to be concerned about whether the object gets its value from a COM API, from a dynamic language such as IronPython, from the HTML Document Object Model (DOM), from reflection, or from somewhere else in the program. ~ &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic" rel="noopener noreferrer"&gt;Microsoft Docs&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;So if you happen to need it, how would you use it and how does it perform? &lt;/p&gt;

&lt;h1&gt;
  
  
  How to Use Dynamic
&lt;/h1&gt;

&lt;p&gt;Using the dynamic keyword is super easy. Any time you would use a regular type or a var, just use dynamic instead. &lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Then you can continue to use your dynamic type in place of any other regular type. &lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The compiler will never throw an error on a dynamic type, but if you aren't careful your program might blow up at runtime if you're using it incorrectly. &lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h1&gt;
  
  
  Dynamic Performance
&lt;/h1&gt;

&lt;p&gt;Lets try to get a glimpse at the performance characteristics of the dynamic keyword. I'm using the ever useful library &lt;a href="https://github.com/dotnet/BenchmarkDotNet" rel="noopener noreferrer"&gt;BenchmarkDotNet&lt;/a&gt;. I've created a couple of examples to compare the performance of dynamic via static typed examples. &lt;/p&gt;

&lt;p&gt;I'm summing an int, concatenating a string, then calling a method on both a local object then a local struct. To view and run the benchmark yourself please visit the &lt;a href="https://github.com/MorganW09/BenchmarkExamples" rel="noopener noreferrer"&gt;github repo&lt;/a&gt;.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Running these benchmark gives us the following numbers:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fxaualirot9uifnzifbcl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fxaualirot9uifnzifbcl.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The two most useful columns are the Mean and Allocated column. The Mean column indicates how long a benchmark took to run. The Allocated column indicates how much heap memory was allocated for a particular benchmark.&lt;/p&gt;

&lt;p&gt;You can see that the dynamic performance was overall worse than actually using types. &lt;/p&gt;

&lt;p&gt;For summing of numbers, dynamic was ~18x slower and allocated memory. &lt;/p&gt;

&lt;p&gt;The string concat was roughly the same performance, which was a little surprising to me. &lt;/p&gt;

&lt;p&gt;Then for the user benchmarks, it was easy to tell that dynamic is not the way to go. &lt;/p&gt;

&lt;h1&gt;
  
  
  Why is Dynamic Slower??
&lt;/h1&gt;

&lt;p&gt;So overall, using dynamic is not very performant, but what about it makes it slower? &lt;/p&gt;

&lt;p&gt;One way we could find out would be to investigate what code is actually compiled. Some features, like the dynamic keyword, extension methods, are natively supported in IL (Intermediate Language), which is what C# gets compiled down into. Before C# is transformed into IL code, it might be first be transformed into some other C# code. What transformations occur for dynamic keywords? &lt;/p&gt;

&lt;p&gt;I took the liberty of installing &lt;a href="https://github.com/0xd4d/dnSpy/releases" rel="noopener noreferrer"&gt;dnSpy&lt;/a&gt;. dnSpy is a debugger and .NET assembly editor. It gives us a picture into what the compiler does with our source code. &lt;/p&gt;

&lt;p&gt;If you download dnSpy, select the dll of this benchmarking library, it will convert the compiled benchmark back into C# for us to view. So what does it look like?&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Dang, that's a lot of extra code the compiler had to generate. The convenience of using the dynamic keyword comes at the cost of all that code. &lt;/p&gt;

&lt;p&gt;The SumOneTo100() method is basically the same as we originally wrote it. Which means what we wrote can be easily transformed into IL. But the DynamicSumOneTo100() is a freakin' mess. A lot of transformations had to occur before converting into IL. &lt;/p&gt;

&lt;p&gt;I've never seen code like this before. Guessing from the example it seems to be dynamically adding the method that is needed right before it is called. &lt;/p&gt;

&lt;p&gt;Our string concat method has even more changes to it, but ironically those changes didn't seem to impact performance as much. &lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Maybe there's just a one time setup cost of using dynamic types? Or summing numbers is a cheaper operation than concating strings, so it would make sense if there was a larger difference when summing numbers versus concating strings. &lt;/p&gt;

&lt;p&gt;I reran the summing numbers benchmark with different values on N. Once when N = 100 (like last time), then also with N = 10,000. If using the dynamic type is just a one time setup, I would imagine that for the N = 10,000 the dynamic and non-dynamic version would be closer in performance. &lt;/p&gt;

&lt;p&gt;So after running that benchmark, it turns out my one time setup cost theory was incorrect. The bad performance was roughly the same for a bigger value of N.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fhcorqhfajuid62btczzm.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fhcorqhfajuid62btczzm.PNG" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I don't really know why the performance of the string benchmark was a lot closer. If anyone out there can help explain why our string benchmark was roughly equivalent while our summing benchmark was drastically different I was love to learn. &lt;/p&gt;

&lt;h1&gt;
  
  
  Parting Thoughts
&lt;/h1&gt;

&lt;p&gt;This might not be a feature you've ever used before, but it's interesting to know that it's there and what it's basic performance is like. &lt;/p&gt;

&lt;p&gt;Overall, if you have a choice to use regular types or dynamic, always go with regular types. The compiler will check your code and then give you better performance. &lt;/p&gt;

&lt;p&gt;If you run into a reason to use dynamic, by all means use it, but know that there are tradeoffs for the convenience of not having the compiler check your types. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;I’m Morgan Kenyon. I’m a .NET developer working in the DFW area. I love solving a good problem and want to talking about the tech I use. If you found this article helpful or thought provoking leave a comment and lets connect over &lt;a href="https://www.linkedin.com/in/morgan-kenyon/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;!&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;a href="https://github.com/MorganW09/BenchmarkExamples" rel="noopener noreferrer"&gt;Github Repo&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
    </item>
    <item>
      <title>Using Suave and F# to Setup CRUD API Routes</title>
      <dc:creator>Morgan Kenyon</dc:creator>
      <pubDate>Mon, 19 Aug 2019 00:51:44 +0000</pubDate>
      <link>https://forem.com/mokenyon/using-suave-and-f-to-setup-crud-api-routes-2gli</link>
      <guid>https://forem.com/mokenyon/using-suave-and-f-to-setup-crud-api-routes-2gli</guid>
      <description>&lt;p&gt;F# is a community driven Functional-First programming language. It’s a multi-paradigm language and interops nicely with C#, but provides a lot of the functional features that make working with it great!&lt;/p&gt;

&lt;p&gt;Lately I’ve spent some time learning F# and through F# discovered Suave:&lt;br&gt;
Suave is a simple web development F# library providing a lightweight web server and a set of combinators to manipulate route flow and task composition.&lt;/p&gt;

&lt;p&gt;As stated, Suave is a web framework that can be used to create apis. When I was researching Suave I didn’t find a great article documenting all the basic CRUD actions that should be used in a REST API.&lt;/p&gt;

&lt;p&gt;This is my attempt to pass along the knowledge I had to piece together over several internet resources. This is not an end to end app, it just documents how to use Suave to setup the necessary routes needed for a simple CRUD app.&lt;/p&gt;

&lt;p&gt;All code will be located on a &lt;a href="https://github.com/MorganW09/SuaveAPI"&gt;github repo&lt;/a&gt;. One of my friends introduced me to Suave . Some of the things he did on his &lt;a href="https://gitlab.com/sNewell/trakr"&gt;personal project&lt;/a&gt; definitely helped me get started in Suave. He's also further down the F# rabbit hole, so check out his project if you're interested.&lt;/p&gt;
&lt;h1&gt;
  
  
  F# and Functional Programming Languages
&lt;/h1&gt;

&lt;p&gt;This article isn’t an introduction to F#. If you’re never encountered the language before, some of the examples here might seem a bit different.&lt;br&gt;
If so, welcome to functional programming languages. My short time learning F# has been quite an eye opening experience.&lt;/p&gt;

&lt;p&gt;Throughout my professional life I’ve used both Java and C#. But I incorrectly assumed that best practices I learned for Java and C# were overall programming best practices. When in reality they were best practices for an object oriented language.&lt;/p&gt;

&lt;p&gt;Functional languages have a very different way of looking at the world. When you start learning a functional language everything is new and the terms can be intimidating.&lt;/p&gt;

&lt;p&gt;Some people get scared off by that fact, but I think it’s worth the time to embrace and learn a new paradigm. That will really only benefit you in the long run.&lt;/p&gt;

&lt;p&gt;If you’re new to functional and F# and want to get started, here is a hour long conference talk called &lt;a href="https://www.youtube.com/watch?v=srQt1NAHYC0"&gt;Functional Design Patterns&lt;/a&gt; by Scott Wlaschin. Scott also blogs at &lt;a href="https://fsharpforfunandprofit.com/"&gt;fsharpforfunandprofit.com&lt;/a&gt; which is a great resource when you’re getting started.&lt;/p&gt;

&lt;p&gt;With that short functional evangelism message behind us, lets dive in.&lt;/p&gt;
&lt;h1&gt;
  
  
  Creating an API
&lt;/h1&gt;

&lt;p&gt;Open up your IDE of choice, I’m using Visual Studio, and create an F# Console App. Use whatever name you prefer, and after creating you should see something similar to the following in your IDE.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ryzv2zot--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/2j4ytx8zu5qjv4qvhm86.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ryzv2zot--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/2j4ytx8zu5qjv4qvhm86.PNG" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Next we’re going to be adding our dependencies. We’ll need to add Suave and Newtonsoft.Json to our project. Right click on “Dependencies” =&amp;gt; “Manage Nuget Packages”, then searching for the two nuget packages and installing them.&lt;/p&gt;

&lt;p&gt;Modify the Program.fs to be the following to create your first route.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Running that project should open up a console that says it launched on 127.0.0.1:8080. If that’s the case for you, you can point your web browser to &lt;a href="http://localhost:8080/"&gt;http://localhost:8080/&lt;/a&gt; and you should see your “Hello World” message.&lt;/p&gt;

&lt;p&gt;I’m also including a postman collection for all routes contained in this example, which is also located on the &lt;a href="https://github.com/MorganW09/SuaveAPI"&gt;github repo&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;With that simple example out of the way. Lets demo a full CRUD architecture for an answer entity.&lt;/p&gt;

&lt;h1&gt;
  
  
  Answer CRUD
&lt;/h1&gt;

&lt;p&gt;So, I could talk a lot more about the four different routes, Create, Read, Update and Delete, or I could just show you the code. So here’s how I would accomplish setting up routes in Suave for all four actions.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;You can use the Postman collection to play around with each route.&lt;/p&gt;

&lt;p&gt;You’ll notice that I have two types, one for new answers and one for answers that already exist.&lt;/p&gt;

&lt;p&gt;You’ll see extensive use of the F# forward pipe operator, “|&amp;gt;”. It’s shorthand for “get the result of the previous line and pass it into the function on this line”.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Those two examples perform the same work, but using the forward pipe operator is much more concise and I think is easier to read.&lt;/p&gt;

&lt;p&gt;If you need to read variables from the path, like I do in the Get answer and Delete answer routes. You’ll need to use pathScan instead of path when defining the route.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Suave does enforce the data types, so if I attempted to pass a string instead of an int Suave wouldn’t be able to find that route because I’m limiting these routes to be an int.&lt;/p&gt;

&lt;p&gt;And lastly I’m a huge fan of how succinct F# is. Once you get used to reading and writing F#, everything can usually be expressed in minimal characters. Writing this in C# would be at least twice as many lines of code, probably more.&lt;/p&gt;

&lt;h1&gt;
  
  
  Final Thoughts
&lt;/h1&gt;

&lt;p&gt;I enjoyed learning Suave and I hope this article helps you get started faster than I was able to. At the moment I’m really enjoying F# and all it’s functional goodness. Stay tuned for future posts on F# and general dotnet programming!&lt;/p&gt;

&lt;p&gt;&lt;em&gt;I’m Morgan Kenyon. I’m a .NET developer working in the DFW area. I find both C# and F# great languages backed by a great ecosystem. I love solving problems and want to continue talking about the tech I use. If you found this article helpful or thought provoking leave a comment and lets connect over &lt;a href="https://www.linkedin.com/in/morgan-kenyon/"&gt;LinkedIn&lt;/a&gt;!&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/MorganW09/SuaveAPI"&gt;Github Repo&lt;/a&gt;&lt;/p&gt;

</description>
      <category>functional</category>
      <category>fsharp</category>
      <category>dotnet</category>
    </item>
    <item>
      <title>Benchmarking The Yield Statement in C#</title>
      <dc:creator>Morgan Kenyon</dc:creator>
      <pubDate>Tue, 13 Aug 2019 03:24:14 +0000</pubDate>
      <link>https://forem.com/mokenyon/benchmarking-the-yield-statement-in-c-2d8g</link>
      <guid>https://forem.com/mokenyon/benchmarking-the-yield-statement-in-c-2d8g</guid>
      <description>&lt;p&gt;Lately I've been interested in benchmarking the features of C# that I use everyday. I've found a lot of my thoughts are based on assumptions instead of facts. Today I'm going to be diving into the Yield statement in C# and seeing how it compares against explicitly creating an enumeration.&lt;/p&gt;

&lt;p&gt;Code is located via the &lt;a href="https://github.com/MorganW09/BenchmarkExamples" rel="noopener noreferrer"&gt;project's Github repo&lt;/a&gt; to see the full benchmark and run it yourself. &lt;/p&gt;

&lt;h1&gt;
  
  
  BenchmarkDotNet
&lt;/h1&gt;

&lt;p&gt;Attaining accurate and valid benchmark results is not trivial. Earlier in my career I resorted to manually timing if I wanted to get a "benchmark." But that's a pretty naive approach to benchmarking. Luckily there's a great library called &lt;a href="https://github.com/dotnet/BenchmarkDotNet" rel="noopener noreferrer"&gt;BenchmarkDotNet&lt;/a&gt; which makes benchmarking easy and does all the hard things for you.&lt;/p&gt;

&lt;p&gt;Check their website or an &lt;a href="https://codeburst.io/getting-started-with-benchmarkdotnet-fb077ba2e6b4" rel="noopener noreferrer"&gt;article I wrote&lt;/a&gt; for an introduction to the library.&lt;/p&gt;

&lt;h1&gt;
  
  
  Yield Statement
&lt;/h1&gt;

&lt;p&gt;So what is the yield statement? The &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield" rel="noopener noreferrer"&gt;Microsoft docs&lt;/a&gt; say:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Using yield to define an iterator removes the need for an explicit extra class (the class that holds the state for an enumeration, see IEnumerator for an example) when you implement the IEnumerable and IEnumerator pattern for a custom collection type.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Take a look at the following example:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Both methods return an IEnumerable, but using the yield statement removes the need to create a list to hold our values as we iterate. &lt;/p&gt;

&lt;p&gt;When I first saw this I didn't really know what to make of it. How did a simple yield statement transform into a IEnumerable return type?&lt;/p&gt;

&lt;p&gt;But after walking through some examples, I began to understand the power of using yield.&lt;/p&gt;

&lt;h2&gt;
  
  
  Yield Example
&lt;/h2&gt;

&lt;p&gt;Take a look at the following example, what would you expect the output to be?&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;20 printed lines? 10 for the "Inserting X" and 10 more for the "Yielding X"?&lt;/p&gt;

&lt;p&gt;When run, the following is printed:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Inserting 0&lt;br&gt;
Inserting 1&lt;br&gt;
Inserting 2&lt;br&gt;
Inserting 3&lt;br&gt;
Inserting 4&lt;br&gt;
Inserting 5&lt;br&gt;
Inserting 6&lt;br&gt;
Inserting 7&lt;br&gt;
Inserting 8&lt;br&gt;
Inserting 9&lt;br&gt;
Yielding 0&lt;br&gt;
Yielding 1&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;If you've never used yield before, take a moment to think through what might be happening? We have declared two loops from 0-9, but only one generated all the values. &lt;/p&gt;

&lt;p&gt;What allowed yield to stop after 1? Whatever it was, it allowed us to avoid generating 80% of the numbers.&lt;/p&gt;
&lt;h1&gt;
  
  
  Why does this happen
&lt;/h1&gt;

&lt;p&gt;This behavior occurs because yield only enumerates values when needed. Instead of generating all 10 values, then returning those values for FindOne() to loop over. Our yield method only returns the next value whenever it is requested.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;That's worth restating&lt;/em&gt;. Yield only returns the next value in the iteration when it is requested. If it's never requested, it's never returned. &lt;/p&gt;

&lt;p&gt;In our example, FindOne() enters the foreach loop and starts the first loop. Calls the GetIEnumerabYield() method, the first time through &lt;em&gt;i&lt;/em&gt; is 0, it hits the yield statement, returns 0 and pauses there. FindOne() gets the 0, that isn't the value it's looking for, so onto the next iteration of FindOne(). On the second iteration of FindOne(), it calls GetIEnumerableYield() again. GetIEnumerableYield() begins from the yield statement, generates the next value in the sequence, 1, hits the yield statement, returns 1 and pauses again. FindOne() has the value it needs and breaks. &lt;/p&gt;

&lt;p&gt;The FindOne() and GetIEnumerableYield() methods are in constant communication. GetIEnumerableYield() is generated values as needed instead of generating them all beforehand. &lt;/p&gt;

&lt;p&gt;If whatever is being created is an expensive operation, using yield could potentially save your program a lot of work.&lt;/p&gt;
&lt;h2&gt;
  
  
  Second Yield Example
&lt;/h2&gt;

&lt;p&gt;Here's another example to get your brain working.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Does this method ever stop running?&lt;/p&gt;

&lt;p&gt;Because we're using a yield statement, yes.&lt;/p&gt;

&lt;p&gt;Even though we're in an infinite while loop, the FindOne() method will stop requesting values after finding the 1. Because yield methods only generate values as needed, only two iteration of the while loop will ever be performed. &lt;/p&gt;

&lt;p&gt;I hope now you're beginning to see some of the possibilities of using a yield statement.&lt;/p&gt;

&lt;h1&gt;
  
  
  Benchmarking Results
&lt;/h1&gt;

&lt;p&gt;Now that we know a bit about what yield is and how it works, lets turn our attention to answering the question of what it's performance is.&lt;/p&gt;

&lt;p&gt;Even though this can be a useful feature, if it's slower we're probably not going to use it. So lets benchmark it.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Here's a simple version of my benchmark. We're basically just going to be generating numbers. One version creates a list, adds to it and returns it. The other just yields those same values. I've created a couple more Benchmarks like this, each one having another layer of nested method calls. If you're curious, all code is on my &lt;a href="https://github.com/MorganW09/BenchmarkExamples" rel="noopener noreferrer"&gt;github&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;If I run all my benchmarks, I get the following result:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fy1o4wodjbn0p7ks4ki5d.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fy1o4wodjbn0p7ks4ki5d.PNG" alt="Benchmark Results"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The important columns to pay attention to is "Mean" and "Allocated". "Mean" is the time it took to run the benchmarks and "Allocated" is the amount of memory used. &lt;/p&gt;

&lt;p&gt;For all but the first one benchmark, yield was significantly faster and used significantly less memory. Especially as the amount of work got bigger, yield was by far the better choice.&lt;/p&gt;

&lt;p&gt;I was not expecting this big a difference between the two different methods. This benchmark surprised me a bit and I'm going to use yield more in the future because of these results. &lt;/p&gt;

&lt;h1&gt;
  
  
  Debugging Note
&lt;/h1&gt;

&lt;p&gt;It's worth noting that the one downside I find when using yield is it makes debugging harder. This has honestly been the reason that I've shied away from using it in the past. &lt;/p&gt;

&lt;p&gt;At no point is there a list that contains all my values for me to investigate. That list doesn't ever get created, only individual values are yielded when needed. &lt;/p&gt;

&lt;p&gt;To be honest, If I'm going to be debugging something for any length of time, sometimes I'll comment out the yield statements and replace them with regular lists. Doing that makes my debugging easier and I can just change it back before checking code in. &lt;/p&gt;

&lt;p&gt;Probably not the best habit, but dealing with yields while debugging isn't the easiest thing to do.&lt;/p&gt;

&lt;p&gt;If anyone has better strategies, I'd love to hear it.&lt;/p&gt;

&lt;h1&gt;
  
  
  Parting Thought
&lt;/h1&gt;

&lt;p&gt;Using a yield statement instead of explicitly creating enumerations has benefits of both speed and performance. But I've found a tradeoff between readability and debug-ability. &lt;/p&gt;

&lt;p&gt;Before benchmarking yield, I had no clue that there was this much of a difference between techniques. Which goes to show why you should benchmark as a developer. Because what you know or assume may just be false. &lt;/p&gt;

&lt;p&gt;Thanks for reading!&lt;/p&gt;

&lt;p&gt;&lt;em&gt;I’m Morgan Kenyon. I’m a .NET developer working in the DFW area. I love solving a good problem and want to talking about the tech I use. If you found this article helpful or thought provoking leave a comment and lets connect over &lt;a href="https://www.linkedin.com/in/morgan-kenyon/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;!&lt;/em&gt;&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
    </item>
  </channel>
</rss>
