<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Claudio Cherubino&#039;s blog &#187; Functional programming</title>
	<atom:link href="http://www.claudiocherubino.it/category/functional-programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.claudiocherubino.it</link>
	<description>Life of a Googler</description>
	<lastBuildDate>Sat, 29 May 2010 18:44:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Spell checking with F#</title>
		<link>http://www.claudiocherubino.it/2010/01/25/spell-checking-with-f/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=spell-checking-with-f</link>
		<comments>http://www.claudiocherubino.it/2010/01/25/spell-checking-with-f/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 19:00:52 +0000</pubDate>
		<dc:creator>claudio</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[Lavoro]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[f#]]></category>
		<category><![CDATA[fsharp]]></category>
		<category><![CDATA[ioprogrammo]]></category>
		<category><![CDATA[jaro-winkler]]></category>
		<category><![CDATA[programming magazine]]></category>
		<category><![CDATA[similarity]]></category>
		<category><![CDATA[spell checker]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://www.claudiocherubino.it/?p=681</guid>
		<description><![CDATA[Some months ago I have written an introductory article on F# for the &#8220;IoProgrammo&#8221; magazine (sorry, Italian only!) and now I have published a second article on the latest issue of the same magazine. This new article covers more advanced topics and is focused on writing a basic spell checker that mixes together the functional [...]]]></description>
			<content:encoded><![CDATA[<p>Some months ago I have written an <a href="http://www.claudiocherubino.it/2009/07/21/f-introductory-article-on-ioprogrammo-magazine/">introductory article</a> on F# for the &#8220;<a href="http://www.ioprogrammo.it/">IoProgrammo</a>&#8221; magazine (sorry, Italian only!) and now I have published a second article on the latest issue of the same magazine.</p>
<p>This new article covers more advanced topics and is focused on writing a basic spell checker that mixes together the functional and object-oriented programming paradigms. </p>
<p>The spell checking algorithm is implemented in functional F# and is based on the <a href="http://en.wikipedia.org/wiki/Jaro-Winkler_distance">Jaro-Winkler similarity distance</a> while the UI is WPF-based and written with OO code.</p>
<p>I hope you will appreciate the article and I&#8217;ll be very happy to get any feedback from the readers.</p>
<p><center><div id="attachment_682" class="wp-caption aligncenter" style="width: 229px"><a href="http://www.claudiocherubino.it/wp-content/uploads/2010/01/ioprogrammo_february2010.jpg"><img src="http://www.claudiocherubino.it/wp-content/uploads/2010/01/ioprogrammo_february2010-219x300.jpg" alt="IoProgrammo - February 2010" title="ioprogrammo_february2010" width="219" height="300" class="size-medium wp-image-682" /></a><p class="wp-caption-text">IoProgrammo - February 2010</p></div></center></p>

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.claudiocherubino.it/2009/07/21/f-introductory-article-on-ioprogrammo-magazine/" title="F# introductory article on IoProgrammo magazine (21 July 2009)">F# introductory article on IoProgrammo magazine</a> (3)</li>
	<li><a href="http://www.claudiocherubino.it/2008/07/01/the-missing-number/" title="The missing number (1 July 2008)">The missing number</a> (13)</li>
	<li><a href="http://www.claudiocherubino.it/2008/02/20/the-2008-winter-scripting-games-pairing-off/" title="The 2008 Winter Scripting Games: Pairing Off (20 February 2008)">The 2008 Winter Scripting Games: Pairing Off</a> (2)</li>
	<li><a href="http://www.claudiocherubino.it/2008/01/22/sorting-odd-and-even-numbers-in-f/" title="Sorting odd and even numbers in F# (22 January 2008)">Sorting odd and even numbers in F#</a> (5)</li>
	<li><a href="http://www.claudiocherubino.it/2008/03/07/run-length-encoding-in-f/" title="Run-Length Encoding in F# (7 March 2008)">Run-Length Encoding in F#</a> (2)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.claudiocherubino.it/2010/01/25/spell-checking-with-f/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Functional programming interview question</title>
		<link>http://www.claudiocherubino.it/2009/08/26/functional-programming-interview-question/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=functional-programming-interview-question</link>
		<comments>http://www.claudiocherubino.it/2009/08/26/functional-programming-interview-question/#comments</comments>
		<pubDate>Wed, 26 Aug 2009 13:24:38 +0000</pubDate>
		<dc:creator>claudio</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[fsharp]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[interview question]]></category>
		<category><![CDATA[joel spolsky]]></category>
		<category><![CDATA[programming exercise]]></category>
		<category><![CDATA[Smart and Get Things Done]]></category>
		<category><![CDATA[starling]]></category>

		<guid isPermaLink="false">http://www.claudiocherubino.it/?p=167</guid>
		<description><![CDATA[I think that examining the hiring process of a company you can understand a lot of what would be working there. As Joel Spolsky wrote, you should only hire people who are Smart and Get Things Done and a good way to be sure that a candidate belongs to this category is testing his/her skills [...]]]></description>
			<content:encoded><![CDATA[<p>I think that examining the hiring process of a company you can understand a lot of what would be working there.</p>
<p>As <em>Joel Spolsky</em> wrote, you should only hire people who are <em>Smart and Get Things Done</em> and a good way to be sure that a candidate belongs to this category is testing his/her skills with a good programming exercise, one easy enough to be solved in 15 minutes but that requires the use of brain.</p>
<p><a href="http://www.starling-software.com/en/index.html">Starling Software</a> clearly describes its <a href="http://www.starling-software.com/en/employment/interview-process">interview process</a> on a page of its website and proposes a couple of sample programs for the potential applicants. In the first problem you are asked to use Haskell to process a given file (obviously we will use F#):</p>
<blockquote><p>
The file <a href="http://www.starling-software.com/employment/input.txt">input.txt</a> contains lists of words, one per line, in two categories, NUMBERS and ANIMALS. A line containing just a category name indicates that the words on the following lines, until the next category name, belong to that category. Read this file as input (on stdin) and print out a) a sorted list of the unique animal names encountered, and b) a list of the number words encountered, along with the count of each. Feel free to chose your output format.
</p></blockquote>
<p>The algorithm to solve the exercise is easy: we read the file line by line and remember the current category (NUMBERS or ANIMALS) in order to add the next words to the appropriate list. When the file is over, we filter duplicates and sort the list of animals and group the numbers together with their counts.</p>
<p>The only problem is knowing how to manage the concept of <em>state</em> of the application in a functional way. In the imperative paradigm you define a variable to keep the state and change its value when you find a new category in the input file. In functional programming you don&#8217;t use state variables instead you use function parameters and recursive calls:</p>
<pre class="brush: fsharp;">
open System
open System.IO

let animals_and_number filename =
  let rec process_line lines category animals numbers =
    match lines with
    | [] -&gt; (animals, numbers)
    | x::xs -&gt; match x with
               | &quot;NUMBERS&quot; -&gt; process_line xs &quot;NUMBERS&quot; animals numbers
               | &quot;ANIMALS&quot; -&gt; process_line xs &quot;ANIMALS&quot; animals numbers
               | x -&gt; match category with
                      | &quot;NUMBERS&quot; -&gt; process_line xs category animals (x :: numbers)
                      | &quot;ANIMALS&quot; -&gt; process_line xs category (x :: animals) numbers
                      | _ -&gt; process_line xs category animals numbers
  let all_lines = File.ReadAllLines(filename) |&gt; Seq.to_list
  process_line all_lines &quot;&quot; [] []

let filename = &quot;input.txt&quot;
let (animals, numbers) = animals_and_number filename
let sorted_animals = animals |&gt; Seq.distinct |&gt; Seq.sort |&gt; Seq.to_list
let counted_words = numbers |&gt; Seq.countBy (fun x -&gt; x) |&gt; Seq.to_list

printf &quot;Animals: %A\n&quot; sorted_animals
printf &quot;Numbers: %A&quot; counted_words
</pre>
<p>The recursive <em>process_line</em> function has four parameters: the list of lines to be processed, the current category (initially an empty string) and the two lists of animals and numbers found so far.</p>
<p>For each new line we first check if it represents one of the categories. In this case we have to <em>change state</em>, i.e. discard the element and recursively call the same function with the correct category parameter.</p>
<p>If the element processed is not a category we only have to add it to the animals or number list, according to the value of the category parameter.</p>
<p>At the end of the <em>animals_and_number</em> function (when <em>lines</em> is empty) we return a tuple made of the two lists created.<br />
The rest of the job is calling some standard library functions to <a href="http://www.claudiocherubino.it/2008/04/23/remove-duplicate-values-from-a-list-in-f/">filter duplicates</a>, sort and count the elements of the sequences.</p>

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.claudiocherubino.it/2008/07/01/the-missing-number/" title="The missing number (1 July 2008)">The missing number</a> (13)</li>
	<li><a href="http://www.claudiocherubino.it/2008/01/22/sorting-odd-and-even-numbers-in-f/" title="Sorting odd and even numbers in F# (22 January 2008)">Sorting odd and even numbers in F#</a> (5)</li>
	<li><a href="http://www.claudiocherubino.it/2008/04/23/remove-duplicate-values-from-a-list-in-f/" title="Remove duplicate values from a List in F# (23 April 2008)">Remove duplicate values from a List in F#</a> (8)</li>
	<li><a href="http://www.claudiocherubino.it/2008/12/28/random-testing-in-f-with-fscheck/" title="Random testing in F# with FsCheck (28 December 2008)">Random testing in F# with FsCheck</a> (2)</li>
	<li><a href="http://www.claudiocherubino.it/2008/01/25/project-euler-in-f-problem-9/" title="Project Euler in F# &#8211; Problem 9 (25 January 2008)">Project Euler in F# &#8211; Problem 9</a> (2)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.claudiocherubino.it/2009/08/26/functional-programming-interview-question/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>F# introductory article on IoProgrammo magazine</title>
		<link>http://www.claudiocherubino.it/2009/07/21/f-introductory-article-on-ioprogrammo-magazine/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=f-introductory-article-on-ioprogrammo-magazine</link>
		<comments>http://www.claudiocherubino.it/2009/07/21/f-introductory-article-on-ioprogrammo-magazine/#comments</comments>
		<pubDate>Tue, 21 Jul 2009 14:00:05 +0000</pubDate>
		<dc:creator>claudio</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[f#]]></category>
		<category><![CDATA[fsharp]]></category>
		<category><![CDATA[ioprogrammo]]></category>
		<category><![CDATA[programming magazine]]></category>
		<category><![CDATA[vigenere cipher]]></category>

		<guid isPermaLink="false">http://www.claudiocherubino.it/?p=162</guid>
		<description><![CDATA[If you understand Italian, you may be interested in reading an introductory article on F# I wrote for the most important Italian programming magazine called &#8220;IoProgrammo&#8221; and that was published a few days ago in the August issue. The article covers the very first steps with F#, from installation to writing a first working sample [...]]]></description>
			<content:encoded><![CDATA[<p>If you understand Italian, you may be interested in reading an introductory article on F# I wrote for the most important Italian programming magazine called &#8220;<em>IoProgrammo</em>&#8221; and that was published a few days ago in the August issue.</p>
<p>The article covers the very first steps with F#, from installation to writing a first working sample application, which can be used to encrypt/decrypt messages using the <a href="http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher">Vigenere cipher</a>.</p>
<p>I hope you can find useful, if you have any comments I&#8217;ll be glad to hear from you.</p>
<p><center><div id="attachment_163" class="wp-caption alignnone" style="width: 227px"><a href="http://www.claudiocherubino.it/wp-content/uploads/2009/07/ioprogrammo_agosto20091.jpg"><img src="http://www.claudiocherubino.it/wp-content/uploads/2009/07/ioprogrammo_agosto2009-217x300.jpg" alt="IoProgrammo - August 2009" title="ioprogrammo_agosto2009" width="217" height="300" class="size-medium wp-image-163" /></a><p class="wp-caption-text">IoProgrammo - August 2009</p></div></center></p>

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.claudiocherubino.it/2010/01/25/spell-checking-with-f/" title="Spell checking with F# (25 January 2010)">Spell checking with F#</a> (0)</li>
	<li><a href="http://www.claudiocherubino.it/2008/07/01/the-missing-number/" title="The missing number (1 July 2008)">The missing number</a> (13)</li>
	<li><a href="http://www.claudiocherubino.it/2008/02/20/the-2008-winter-scripting-games-pairing-off/" title="The 2008 Winter Scripting Games: Pairing Off (20 February 2008)">The 2008 Winter Scripting Games: Pairing Off</a> (2)</li>
	<li><a href="http://www.claudiocherubino.it/2008/01/22/sorting-odd-and-even-numbers-in-f/" title="Sorting odd and even numbers in F# (22 January 2008)">Sorting odd and even numbers in F#</a> (5)</li>
	<li><a href="http://www.claudiocherubino.it/2008/03/07/run-length-encoding-in-f/" title="Run-Length Encoding in F# (7 March 2008)">Run-Length Encoding in F#</a> (2)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.claudiocherubino.it/2009/07/21/f-introductory-article-on-ioprogrammo-magazine/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Merging arrays</title>
		<link>http://www.claudiocherubino.it/2009/06/13/merging-arrays/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=merging-arrays</link>
		<comments>http://www.claudiocherubino.it/2009/06/13/merging-arrays/#comments</comments>
		<pubDate>Sat, 13 Jun 2009 13:39:36 +0000</pubDate>
		<dc:creator>claudio</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[interview question]]></category>
		<category><![CDATA[job interview]]></category>

		<guid isPermaLink="false">http://www.claudiocherubino.it/?p=150</guid>
		<description><![CDATA[Thanks to interviewpattern.com I discovered that one of the classical Amazon interview questions is writing a snippet of code to merge two sorted arrays: &#8220;Suppose we have two sorted arrays A[] of m elements and B[] of n elements. Write a function merge which would merge this two arrays into new sorted array C[] in [...]]]></description>
			<content:encoded><![CDATA[<p>Thanks to <a href="http://interviewpattern.com/post/Merging-Arrays-Interview-Question.aspx">interviewpattern.com</a> I discovered that one of the classical Amazon interview questions is writing a snippet of code to merge two sorted arrays:</p>
<blockquote><p>&#8220;Suppose we have two sorted arrays A[] of m elements and B[] of n elements. Write a function merge which would merge this two arrays into new sorted array C[] in O(n) time as shown on the picture&#8221;.</p></blockquote>
<p><center><a href="http://www.claudiocherubino.it/wp-content/uploads/2009/06/MergeArrays.png"><img src="http://www.claudiocherubino.it/wp-content/uploads/2009/06/MergeArrays-300x121.png" alt="MergeArrays" title="MergeArrays" width="300" height="121" class="alignnone size-medium wp-image-151" /></a><br />
</center></p>
<p>This problem is also a classical exercise for functional programming learners that shows the conciseness of functional code in comparison with imperative one.</p>
<p>The solution presented on the original page is written in C# and is longer than 40 lines of code, while we can solve the same problem in F# with less than 10 lines:</p>
<pre class="brush: fsharp;">
let rec merge_arrays a b =
  match (a, b) with
  | (a, []) -&gt; a
  | ([], b) -&gt; b
  | (x::xs, y::ys) -&gt; if (x &lt; y) then
                        (x :: (merge_arrays xs (y::ys)))
                      else
                        (y :: (merge_arrays (x::xs) ys))
</pre>
<p>Besides being shorter, I also find the functional code to be much easier to understand. Do you agree with me?</p>

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.claudiocherubino.it/2008/07/01/the-missing-number/" title="The missing number (1 July 2008)">The missing number</a> (13)</li>
	<li><a href="http://www.claudiocherubino.it/2008/06/10/google-interview-question-product-of-other-elements-in-an-array-in-on/" title="Google Interview Question: Product of other Elements in an Array in O(n) (10 June 2008)">Google Interview Question: Product of other Elements in an Array in O(n)</a> (10)</li>
	<li><a href="http://www.claudiocherubino.it/2009/01/23/facebook-fizzbuzz/" title="Facebook FizzBuzz (23 January 2009)">Facebook FizzBuzz</a> (3)</li>
	<li><a href="http://www.claudiocherubino.it/2009/08/26/functional-programming-interview-question/" title="Functional programming interview question (26 August 2009)">Functional programming interview question</a> (1)</li>
	<li><a href="http://www.claudiocherubino.it/2008/07/22/balanced-parenthesis/" title="Balanced parenthesis (22 July 2008)">Balanced parenthesis</a> (5)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.claudiocherubino.it/2009/06/13/merging-arrays/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Luhn algorithm in F#</title>
		<link>http://www.claudiocherubino.it/2009/04/15/luhn-algorithm-in-f/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=luhn-algorithm-in-f</link>
		<comments>http://www.claudiocherubino.it/2009/04/15/luhn-algorithm-in-f/#comments</comments>
		<pubDate>Wed, 15 Apr 2009 11:01:34 +0000</pubDate>
		<dc:creator>claudio</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[checksum]]></category>
		<category><![CDATA[credit card numbers]]></category>
		<category><![CDATA[digits]]></category>
		<category><![CDATA[error detection]]></category>
		<category><![CDATA[f#]]></category>
		<category><![CDATA[fsharp]]></category>
		<category><![CDATA[luhn algorithm]]></category>
		<category><![CDATA[modulus]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://www.claudiocherubino.it/?p=122</guid>
		<description><![CDATA[The Luhn algorithm is a simple error detection formula based on the modulus operator which is widely used to validate credit card numbers or Canadian Social Insurance Numbers. This checksum function can detect any single-digit error and operates verifying the number against its included check digit. The algorithm is made of three steps: 1) starting [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://en.wikipedia.org/wiki/Luhn_algorithm">Luhn algorithm</a> is a simple error detection formula based on the modulus operator which is widely used to validate credit card numbers or Canadian Social Insurance Numbers.</p>
<p>This checksum function can detect any single-digit error and operates verifying the number against its included check digit.</p>
<p>The algorithm is made of three steps:</p>
<p>1) starting from the rightmost digit and moving left, double the value of every second digit (or digits in even positions);<br />
2) sum all resulting digits together with the original ones that were untouched;<br />
3) if the result is a multiple of 10 (i.e. the result modulus 10 is zero) then the input value is valid.</p>
<p>This simple algorithm can be implemented with a few F# lines of code:</p>
<pre class="brush: fsharp;">
#light
open System

let double_digit n =
  let double = n * 2
  if (double &gt; 9) then
    double - 9
  else
    double

let rec luhn_loop isEven acc input =
    match input with
    | [] -&gt; acc % 10 = 0
    | x :: xs -&gt; let num = Int32.Parse(x.ToString())
                 if (isEven) then
                   luhn_loop (not isEven) (acc + (double_digit num)) xs
                 else
                   luhn_loop (not isEven) (acc + num) xs

let luhn n = n.ToString() |&gt; Seq.to_array |&gt; Array.rev |&gt; Seq.to_list |&gt; luhn_loop false 0
</pre>
<p>I separated from the main loop the <em>double_digit</em> function, which takes a digit and multiplies it by two. If the result has two digits (i.e. it is greater than 9) with sum together the two digits (i.e. subtract 9 from the number), otherwise we simply return it.</p>
<p>The <em>luhn_loop</em> function iterates over the list of digit that is obtained by taking the original number, converting it into an array of digits and reversing it.<br />
Inside each iteration we take into account a single digit, double it if it is placed in an even position and sum it to the accumulator.</p>
<p>When the list of digits to be examined is empty we are done with the loop and we just have to check if the value stored in the accumulator is evenly divisible by 10.</p>

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.claudiocherubino.it/2009/03/20/project-euler-in-f-problem-52/" title="Project Euler in F# &#8211; Problem 52 (20 March 2009)">Project Euler in F# &#8211; Problem 52</a> (2)</li>
	<li><a href="http://www.claudiocherubino.it/2008/04/30/project-euler-in-f-problem-48/" title="Project Euler in F# &#8211; Problem 48 (30 April 2008)">Project Euler in F# &#8211; Problem 48</a> (4)</li>
	<li><a href="http://www.claudiocherubino.it/2008/10/08/project-euler-in-f-problem-36/" title="Project Euler in F# &#8211; Problem 36 (8 October 2008)">Project Euler in F# &#8211; Problem 36</a> (1)</li>
	<li><a href="http://www.claudiocherubino.it/2008/09/19/project-euler-in-f-problem-25/" title="Project Euler in F# &#8211; Problem 25 (19 September 2008)">Project Euler in F# &#8211; Problem 25</a> (3)</li>
	<li><a href="http://www.claudiocherubino.it/2008/01/29/project-euler-in-f-problem-20/" title="Project Euler in F# &#8211; Problem 20 (29 January 2008)">Project Euler in F# &#8211; Problem 20</a> (1)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.claudiocherubino.it/2009/04/15/luhn-algorithm-in-f/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Brainfuck interpreter in F#</title>
		<link>http://www.claudiocherubino.it/2009/02/12/brainfuck-interpreter-in-f/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=brainfuck-interpreter-in-f</link>
		<comments>http://www.claudiocherubino.it/2009/02/12/brainfuck-interpreter-in-f/#comments</comments>
		<pubDate>Thu, 12 Feb 2009 08:46:18 +0000</pubDate>
		<dc:creator>claudio</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[brainfuck]]></category>
		<category><![CDATA[esoteric languages]]></category>
		<category><![CDATA[f#]]></category>
		<category><![CDATA[fsharp]]></category>
		<category><![CDATA[interpreter]]></category>
		<category><![CDATA[parser]]></category>

		<guid isPermaLink="false">http://www.claudiocherubino.it/?p=104</guid>
		<description><![CDATA[Brainfuck is an esoteric programming language whose grammar consists of only eight commands, written as a single character each. Besides this minimalistic structure, the language is Turing-complete but writing (and reading) Brainfuck code is very hard. The Brainfuck machine uses a finite-length tape (usually 30000 byte cells long) and two pointers: an instruction pointer and [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Brainfuck">Brainfuck</a> is an <em>esoteric programming language</em> whose grammar consists of only eight commands, written as a single character each.</p>
<p>Besides this minimalistic structure, the language is <em><a href="http://en.wikipedia.org/wiki/Turing-complete">Turing-complete</a></em> but writing (and reading) Brainfuck code is very hard.</p>
<p>The Brainfuck machine uses a finite-length tape (usually 30000 byte cells long) and two pointers: an instruction pointer and a data pointer.</p>
<p>The former scans the source code and executes one instruction at a time, while the latter is used to increase or decrease the value of the cell that it is pointing.</p>
<p>This structure can be represented by the following F# type, called <em>BFState</em>:</p>
<pre class="brush: fsharp;">
type BFState =
  { mutable program : string ;        // program being interpreted
    mutable memory : int[] ;          // memory
    mutable pc : int ;                // current program counter
    mutable pos : int }               // current pointer position
</pre>
<p>We define then a function to initialize our Brainfuck machine given the size of the memory tape and the source code, that basically zeroes all memory cells and the two pointers:</p>
<pre class="brush: fsharp;">
let initState memSize code  =
  { program = code;
    memory = Array.zero_create memSize;
    pc = 0;
    pos = 0; }
</pre>
<p>We reach the end of the program when the program counter steps beyond the end of the code (i.e. the length of the string containing the source):</p>
<pre class="brush: fsharp;">
let isEnd (state : BFState) =
  state.pc &gt;= state.program.Length
</pre>
<p>The following two functions are used to move the program counter one step towards the end or the beginning of the source code:</p>
<pre class="brush: fsharp;">
let nextCommand (state : BFState) =
  { program = state.program ; memory = state.memory ; pc = state.pc + 1 ; pos = state.pos }

let previousCommand (state : BFState) =
  { program = state.program ; memory = state.memory ; pc = state.pc - 1 ; pos = state.pos }
</pre>
<p><em>getMem</em> and <em>setMem</em> are two auxiliary functions that can be used to retrieve or set the value of the memory cell pointed by the data pointer:</p>
<pre class="brush: fsharp;">
let getMem (state : BFState) =
  state.memory.[state.pos]

let setMem (state : BFState) value =
  state.memory.[state.pos] &lt;- value
  state.memory
</pre>
<p>Similarly, we have two functions to read and write from the console, which is the behavior of the &#8216;,&#8217; and &#8216;.&#8217; commands respectively:</p>
<pre class="brush: fsharp;">
let outputByte (state : BFState) =
  Console.Write (Convert.ToChar(state.memory.[state.pos]))
  nextCommand state

let readByte (state : BFState) =
  state.memory.[state.pos] &lt;- Console.Read()
  nextCommand state
</pre>
<p>When the command to perform is &#8216;[', if the byte at the data pointer is zero we have to jump to the first matching ']&#8216; character following the current position:</p>
<pre class="brush: fsharp;">
let rec moveToForwardMatch (state : BFState) =
  match state.program.[state.pc] with
  | ']' -&gt; (nextCommand state)
  | _ -&gt; moveToForwardMatch (nextCommand state)
</pre>
<p>The complementary command is &#8216;]&#8217;, that goes back to the matching &#8216;[' character when the byte at the data pointer is non-zero:</p>
<pre class="brush: fsharp;">
let rec moveToPreviousMatch (state : BFState) =
  match state.program.[state.pc] with
  | &#8216;[' -&gt; (nextCommand state)
  | _ -&gt; moveToPreviousMatch (previousCommand state)
</pre>
<p>We have now all the tools required to parse Brainfuck code, so we only need to write the logic to select the action to perform according to the command analyzed in a single step.</p>
<p>Each command takes a <em>BFState</em> and returns a new <em>BFState</em>. Any character different from the eight allowed will be simply ignored:</p>
<pre class="brush: fsharp;">
let step (state : BFState) =
  match state.program.[state.pc] with
  | &#8216;+&#8217; -&gt; { program = state.program ; memory = setMem state (getMem state + 1) ; pc = state.pc + 1 ; pos = state.pos }
  | &#8216;-&#8217; -&gt; { program = state.program ; memory = setMem state (getMem state &#8211; 1) ; pc = state.pc + 1 ; pos = state.pos }
  | &#8216;&lt;&#8217; -&gt; { program = state.program ; memory = state.memory ; pc = state.pc + 1 ; pos = state.pos &#8211; 1}
  | &#8216;&gt;&#8217; -&gt; { program = state.program ; memory = state.memory ; pc = state.pc + 1 ; pos = state.pos + 1}
  | &#8216;[' -&gt; if (state.memory.[state.pos] = 0) then moveToForwardMatch state else nextCommand state
  | &#8216;]&#8217; -&gt; if (state.memory.[state.pos] &lt;&gt; 0) then moveToPreviousMatch state else nextCommand state
  | &#8216;.&#8217; -&gt; outputByte state
  | &#8216;,&#8217; -&gt; readByte state
  | _ -&gt; nextCommand state // ignore any non-command character
</pre>
<p>The parser, which could be the only publicly available function, will take care of initializing the state and recursively step through the code, one instruction at a time, until the end of the source:</p>
<pre class="brush: fsharp;">
let parse memSize code =
  let rec run (state : BFState) =
    if (not (isEnd state)) then
       run (step state)
  initState memSize code |&gt; run
</pre>
<p>You can find a repository of Brainfuck sample programs at this site: <a href="http://esoteric.sange.fi/brainfuck/bf-source/prog/">http://esoteric.sange.fi/brainfuck/bf-source/prog/</a>, the following code contains the classic <em>Hello World!</em> and how to parse it using the interpreter we just wrote:</p>
<pre class="brush: fsharp;">
let code = &quot;&gt;+++++++++[&lt;++++++++&gt;-]&lt;.&gt;+++++++[&lt;++++&gt;-]&lt;+.+++++++..+++.&gt;&gt;&gt;++++++++[&lt;++++&gt;-]&lt;.&gt;&gt;&gt;++++++++++[&lt;+++++++++&gt;-]&lt;---.&lt;&lt;&lt;&lt;.+++.------.--------.&gt;&gt;+.&quot;

parse 30000 code
</pre>
<p>The whole Brainfuck interpreter code can be found just below, feel free to take it and dissect it:</p>
<pre class="brush: fsharp;">
#light
open System

type BFState =
  { mutable program : string ;        // program being interpreted
    mutable memory : int[] ;          // memory
    mutable pc : int ;                // current program counter
    mutable pos : int }               // current pointer position

let initState memSize code  =
  { program = code;
    memory = Array.zero_create memSize;
    pc = 0;
    pos = 0; }

let isEnd (state : BFState) =
  state.pc &gt;= state.program.Length

let nextCommand (state : BFState) =
  { program = state.program ; memory = state.memory ; pc = state.pc + 1 ; pos = state.pos }

let previousCommand (state : BFState) =
  { program = state.program ; memory = state.memory ; pc = state.pc - 1 ; pos = state.pos }

let getMem (state : BFState) =
  state.memory.[state.pos]

let setMem (state : BFState) value =
  state.memory.[state.pos] &lt;- value
  state.memory

let rec moveToForwardMatch (state : BFState) =
  match state.program.[state.pc] with
  | ']' -&gt; (nextCommand state)
  | _ -&gt; moveToForwardMatch (nextCommand state)

let rec moveToPreviousMatch (state : BFState) =
  match state.program.[state.pc] with
  | '[' -&gt; (nextCommand state)
  | _ -&gt; moveToPreviousMatch (previousCommand state)

let outputByte (state : BFState) =
  Console.Write (Convert.ToChar(state.memory.[state.pos]))
  nextCommand state

let readByte (state : BFState) =
  state.memory.[state.pos] &lt;- Console.Read()
  nextCommand state

let step (state : BFState) =
  match state.program.[state.pc] with
  | '+' -&gt; { program = state.program ; memory = setMem state (getMem state + 1) ; pc = state.pc + 1 ; pos = state.pos }
  | '-' -&gt; { program = state.program ; memory = setMem state (getMem state - 1) ; pc = state.pc + 1 ; pos = state.pos }
  | '&lt;' -&gt; { program = state.program ; memory = state.memory ; pc = state.pc + 1 ; pos = state.pos - 1}
  | '&gt;' -&gt; { program = state.program ; memory = state.memory ; pc = state.pc + 1 ; pos = state.pos + 1}
  | '[' -&gt; if (state.memory.[state.pos] = 0) then moveToForwardMatch state else nextCommand state
  | ']' -&gt; if (state.memory.[state.pos] &lt;&gt; 0) then moveToPreviousMatch state else nextCommand state
  | '.' -&gt; outputByte state
  | ',' -&gt; readByte state
  | _ -&gt; nextCommand state // ignore any non-command character

let parse memSize code =
  let rec run (state : BFState) =
    if (not (isEnd state)) then
       run (step state)
  initState memSize code |&gt; run
</pre>

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.claudiocherubino.it/2008/07/01/the-missing-number/" title="The missing number (1 July 2008)">The missing number</a> (13)</li>
	<li><a href="http://www.claudiocherubino.it/2008/02/20/the-2008-winter-scripting-games-pairing-off/" title="The 2008 Winter Scripting Games: Pairing Off (20 February 2008)">The 2008 Winter Scripting Games: Pairing Off</a> (2)</li>
	<li><a href="http://www.claudiocherubino.it/2010/01/25/spell-checking-with-f/" title="Spell checking with F# (25 January 2010)">Spell checking with F#</a> (0)</li>
	<li><a href="http://www.claudiocherubino.it/2008/01/22/sorting-odd-and-even-numbers-in-f/" title="Sorting odd and even numbers in F# (22 January 2008)">Sorting odd and even numbers in F#</a> (5)</li>
	<li><a href="http://www.claudiocherubino.it/2008/03/07/run-length-encoding-in-f/" title="Run-Length Encoding in F# (7 March 2008)">Run-Length Encoding in F#</a> (2)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.claudiocherubino.it/2009/02/12/brainfuck-interpreter-in-f/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Facebook FizzBuzz</title>
		<link>http://www.claudiocherubino.it/2009/01/23/facebook-fizzbuzz/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=facebook-fizzbuzz</link>
		<comments>http://www.claudiocherubino.it/2009/01/23/facebook-fizzbuzz/#comments</comments>
		<pubDate>Fri, 23 Jan 2009 20:54:59 +0000</pubDate>
		<dc:creator>claudio</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[coding horror]]></category>
		<category><![CDATA[f#]]></category>
		<category><![CDATA[facebook]]></category>
		<category><![CDATA[fizzbuzz]]></category>
		<category><![CDATA[fsharp]]></category>
		<category><![CDATA[HoppityHop]]></category>
		<category><![CDATA[interview question]]></category>
		<category><![CDATA[Jeff Atwood]]></category>
		<category><![CDATA[job interview]]></category>

		<guid isPermaLink="false">http://www.claudiocherubino.it/?p=99</guid>
		<description><![CDATA[Have you ever tried looking for &#8220;FizzBuzz&#8221; on a search engine? If you do, you&#8217;ll surely land on this page on Coding Horror, the blog written by Jeff Atwood. To make a long story short, Jeff states that the vast majority of the developers is unable to write a tiny program that should take no [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever tried looking for &#8220;<strong>FizzBuzz</strong>&#8221; on a search engine?</p>
<p>If you do, you&#8217;ll surely land on <a href="http://www.codinghorror.com/blog/archives/000781.html">this page</a> on <a href="http://www.codinghorror.com/blog/">Coding Horror</a>, the blog written by <strong>Jeff Atwood</strong>.</p>
<p>To make a long story short, Jeff states that the vast majority of the developers is unable to write a tiny program that should take no more than 10 minutes to code.</p>
<p>This is the <em>famous</em> FizzBuzz problem:</p>
<blockquote><p>Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. </p></blockquote>
<p>You should be outraged now, if you aren&#8217;t I hope you don&#8217;t make a living as a developer! <img src='http://www.claudiocherubino.it/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>I found out that Facebook also considers FizzBuzz as a good starting test for job applicants. There is a <a href="http://www.facebook.com/jobs_puzzles/index.php">programming puzzles page</a>, where you can find a set of good problems, ranging from blindingly easy to very hard.</p>
<p>The first one is called <a href="http://www.facebook.com/jobs_puzzles/index.php?puzzle_id=7">HoppityHop!</a> and it is just a variation of the good old FizzBuzz:</p>
<blockquote><p>The program should iterate over all integers (inclusive) from 1 to the number expressed by the input file. For example, if the file contained the number 10, the submission should iterate over 1 through 10. At each integer value in this range, the program may possibly (based upon the following rules) output a single string terminating with a newline.</p>
<p>    * For integers that are evenly divisible by three, output the exact string Hoppity, followed by a newline.<br />
    * For integers that are evenly divisible by five, output the exact string Hophop, followed by a newline.<br />
    * For integers that are evenly divisble by both three and five, do not do any of the above, but instead output the exact string Hop, followed by a newline.</p></blockquote>
<p>Being a developer myself I couldn&#8217;t resist writing a solution for this problem, obviously in F#:</p>
<pre class="brush: fsharp;">
#light

let HoppityHop n =
  let printHop x =
    match x with
    | x when (x % 15 = 0)-&gt; printfn &quot;Hop&quot;
    | x when (x % 3 = 0) -&gt; printfn &quot;Hoppity&quot;
    | x when (x % 5 = 0) -&gt; printfn &quot;Hophop&quot;
    | _ -&gt; ()
  [1 .. n] |&gt; Seq.iter printHop
</pre>
<p>I know many of you will feel the urge to suggest a better solution, you&#8217;re welcome, the comment area is yours to use!</p>

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.claudiocherubino.it/2008/07/01/the-missing-number/" title="The missing number (1 July 2008)">The missing number</a> (13)</li>
	<li><a href="http://www.claudiocherubino.it/2008/07/22/balanced-parenthesis/" title="Balanced parenthesis (22 July 2008)">Balanced parenthesis</a> (5)</li>
	<li><a href="http://www.claudiocherubino.it/2008/02/20/the-2008-winter-scripting-games-pairing-off/" title="The 2008 Winter Scripting Games: Pairing Off (20 February 2008)">The 2008 Winter Scripting Games: Pairing Off</a> (2)</li>
	<li><a href="http://www.claudiocherubino.it/2010/01/25/spell-checking-with-f/" title="Spell checking with F# (25 January 2010)">Spell checking with F#</a> (0)</li>
	<li><a href="http://www.claudiocherubino.it/2008/01/22/sorting-odd-and-even-numbers-in-f/" title="Sorting odd and even numbers in F# (22 January 2008)">Sorting odd and even numbers in F#</a> (5)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.claudiocherubino.it/2009/01/23/facebook-fizzbuzz/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Random testing in F# with FsCheck</title>
		<link>http://www.claudiocherubino.it/2008/12/28/random-testing-in-f-with-fscheck/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=random-testing-in-f-with-fscheck</link>
		<comments>http://www.claudiocherubino.it/2008/12/28/random-testing-in-f-with-fscheck/#comments</comments>
		<pubDate>Sun, 28 Dec 2008 19:31:01 +0000</pubDate>
		<dc:creator>claudio</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[f#]]></category>
		<category><![CDATA[fscheck]]></category>
		<category><![CDATA[fsharp]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[quickcheck]]></category>
		<category><![CDATA[rsa]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://www.claudiocherubino.it/?p=84</guid>
		<description><![CDATA[One of the emerging trends in software development is TDD or Test-Driven Development, a methodology based on writing tests first and then coding in order to pass the tests. Besides unit testing libraries inherited by the .Net Framework, F# can now count on FsCheck, a random testing framework cloned from Haskell&#8217;s QuickCheck. A random testing [...]]]></description>
			<content:encoded><![CDATA[<p>One of the emerging trends in software development is <strong>TDD</strong> or <strong>Test-Driven Development</strong>, a methodology based on writing tests first and then coding in order to pass the tests.</p>
<p>Besides unit testing libraries inherited by the .Net Framework, F# can now count on <a href="http://www.codeplex.com/fscheck">FsCheck</a>, a random testing framework cloned from Haskell&#8217;s <a href="http://en.wikipedia.org/wiki/QuickCheck">QuickCheck</a>.</p>
<p>A random testing library generates a set of test cases and attempts to falsify the properties defined by the developer.</p>
<p>This approach is not exhaustive but if all the tests of large enough test suite are passed we can safely assume that the code is correct.</p>
<p>Let&#8217;s see how to get started using <a href="http://www.codeplex.com/fscheck">FsCheck</a> to validate the <a href="http://www.claudiocherubino.it/2008/12/01/implementation-of-rsa-in-f/">RSA implementation</a> written some time ago.</p>
<p>The first step is to download the latest release (currently 0.3) of FsCheck from the <a href="http://www.codeplex.com/fscheck/Release/ProjectReleases.aspx#ReleaseFiles">Download page</a>.</p>
<p>You can either get the binaries or the source code, that also contains an example console application.</p>
<p>Assuming that you downloaded the binaries, you have then to open/create an F# application and add a Reference (<em>Project &#8211; Add Reference</em>) to the FsCheck.dll library file:</p>
<p><center><div id="attachment_88" class="wp-caption alignnone" style="width: 231px"><img src="http://www.claudiocherubino.it/wp-content/uploads/2008/12/fscheck1.png" alt="Project referencing FsCheck library" title="FsCheck" width="221" height="183" class="size-full wp-image-88" /><p class="wp-caption-text">Project referencing FsCheck library</p></div></center></p>
<p>In order to use the methods provided by FsCheck we have to include its namescope into our code by adding a <em>open FsCheck</em> clause at the beginning of our program.</p>
<p>For the sake of example, let&#8217;s fix the two distinct random prime numbers <em>p</em> and <em>q</em> and the public exponent <em>e</em>.</p>
<p>We have then to define our first property, that I&#8217;m going to call <em>prop_rsa</em>, which basically asserts that decrypting a message that was previously encrypted we get back the original message.</p>
<p>In order to run a property <em>prop_myproperty</em> we just have to run <em>quickCheck myproperty</em>, so in this case we&#8217;ll run <em>quickCheck prop_rsa</em>.</p>
<pre class="brush: fsharp;">
#light
open System
open FsCheck

// RSA sample data
let p = 61
let q = 53
let e = 17
let n = p * q
let d = private_exponent e p q

let prop_rsa message =
  let encrypted = encrypt message e n
  decrypt encrypted d n = message

quickCheck prop_rsa

Console.ReadKey() |&gt; ignore
</pre>
<p>If everything goes well, we should see a console window like the following one, with the number of tests passed (by default, FsCheck generates 100 test cases).</p>
<p><center><div id="attachment_90" class="wp-caption alignnone" style="width: 310px"><a href="http://www.claudiocherubino.it/wp-content/uploads/2008/12/fscheck_passedtests.png"><img src="http://www.claudiocherubino.it/wp-content/uploads/2008/12/fscheck_passedtests-300x108.png" alt="FsCheck shows the number of passed tests" title="FsCheck Passed Tests" width="300" height="108" class="size-medium wp-image-90" /></a><p class="wp-caption-text">FsCheck shows the number of passed tests</p></div></center></p>
<p>If a test fails, FsCheck will stop the execution and show which test failed. If you want to see all the generated test cases, you can run <em>verboseCheck</em> instead of <em>quickCheck</em>.</p>
<p>The next step should be writing a custom generator in order to generate not only the message but also the prime numbers and the public exponent, but I think we can cover that in a future post.</p>
<p>You can <strong>download the complete solution</strong> <a href='http://www.claudiocherubino.it/wp-content/uploads/2008/12/fschecktest.zip'>here</a>.</p>

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.claudiocherubino.it/2008/04/23/remove-duplicate-values-from-a-list-in-f/" title="Remove duplicate values from a List in F# (23 April 2008)">Remove duplicate values from a List in F#</a> (8)</li>
	<li><a href="http://www.claudiocherubino.it/2008/02/07/project-euler-in-f-problem-5/" title="Project Euler in F# &#8211; Problem 5 (7 February 2008)">Project Euler in F# &#8211; Problem 5</a> (7)</li>
	<li><a href="http://www.claudiocherubino.it/2008/07/01/the-missing-number/" title="The missing number (1 July 2008)">The missing number</a> (13)</li>
	<li><a href="http://www.claudiocherubino.it/2008/02/20/the-2008-winter-scripting-games-pairing-off/" title="The 2008 Winter Scripting Games: Pairing Off (20 February 2008)">The 2008 Winter Scripting Games: Pairing Off</a> (2)</li>
	<li><a href="http://www.claudiocherubino.it/2010/01/25/spell-checking-with-f/" title="Spell checking with F# (25 January 2010)">Spell checking with F#</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.claudiocherubino.it/2008/12/28/random-testing-in-f-with-fscheck/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Implementation of RSA in F#</title>
		<link>http://www.claudiocherubino.it/2008/12/01/implementation-of-rsa-in-f/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=implementation-of-rsa-in-f</link>
		<comments>http://www.claudiocherubino.it/2008/12/01/implementation-of-rsa-in-f/#comments</comments>
		<pubDate>Mon, 01 Dec 2008 19:56:45 +0000</pubDate>
		<dc:creator>claudio</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[encryption]]></category>
		<category><![CDATA[f#]]></category>
		<category><![CDATA[factorization]]></category>
		<category><![CDATA[gcd]]></category>
		<category><![CDATA[greatest common divisor]]></category>
		<category><![CDATA[modulus]]></category>
		<category><![CDATA[prime numbers]]></category>
		<category><![CDATA[rsa]]></category>
		<category><![CDATA[scheme]]></category>
		<category><![CDATA[totient]]></category>

		<guid isPermaLink="false">http://www.claudiocherubino.it/?p=68</guid>
		<description><![CDATA[During my university course I had to learn and use two functional programming languages: Haskell and Scheme. I fell in love with the former but I never managed to do the same with the syntax of Scheme and the incredibly huge number of parenthesis you have to type in order for your code to work! [...]]]></description>
			<content:encoded><![CDATA[<p>During my university course I had to learn and use two functional programming languages: <strong>Haskell</strong> and <strong>Scheme</strong>. I fell in love with the former but I never managed to do the same with the syntax of Scheme and the incredibly huge number of parenthesis you have to type in order for your code to work!</p>
<p>That&#8217;s why I decided to <del datetime="2008-12-01T19:24:42+00:00">steal</del> borrow <a href="http://matt.might.net/articles/implementation-of-rsa-public-key-cryptography-algorithm-in-scheme-dialect-of-lisp/">a short implementation of the RSA algorithm written in Scheme</a> and translate it into F#.</p>
<p>As you may know, <a href="http://en.wikipedia.org/wiki/RSA">RSA</a> is an algorithm used for <strong>public-key encryption</strong> based on prime numbers and factorization that is widely use on the web to secure e-commerce transactions.</p>
<p>At the end of the following code there is also a working example that can be executed to better understand the steps required to encrypt and decrypt a message (in this case a single number):</p>
<pre class="brush: fsharp;">
#light
// Modulus operator that handles negative numbers correctly
let modulus n m =
  ((n % m) + m) % m

// Greater Common Divisor
let rec gcd a b =
  match b with
  | b when b = 0 -&gt; a
  | b -&gt; gcd b (a % b)

// extended_gcd = (x,y), such that a*x + b*y = gcd(a,b)
let rec extended_gcd a b =
  if (a % b = 0) then
    (0, 1)
  else
    let (x, y) = extended_gcd b (a % b)
    (y, x - y * (a / b))

// modulo_inverse(a,n) = b, such that a*b = 1 [mod n]
let modulo_inverse a n =
  let (x, y) = extended_gcd a n
  modulus x n

// totient(n) = (p - 1)*(q - 1),
// where pq is the prime factorization of n.
let totient p q = (p - 1) * (q - 1)

// square(x) = x^2
let square x = x * x

// modulo-power(base,exp,n) = base^exp [mod n]
let rec modulo_power b exp n =
  if (exp = 0) then
    1
  else
    if (exp % 2 = 1) then
      (((modulo_power b (exp - 1) n) * b) % n)
    else
      ((square (modulo_power b (exp / 2) n)) % n)

// RSA routines.

// A legal public exponent e is between
// 1 and totient(n), and gcd(e,totient(n)) = 1
let is_legal_public_exponent e p q =
  (1 &lt; e) &amp;&amp; (e &lt; (totient p q)) &amp;&amp; (1 = (gcd e (totient p q)))

// The private exponent is the inverse of the public exponent, mod n.
let private_exponent e p q =
  if (is_legal_public_exponent e p q) then
    modulo_inverse e (totient p q)
  else
    raise (new System.Exception(&quot;Not a legal public exponent for that modulus&quot;))

// An encrypted message is c = m^e [mod n]
let encrypt m e n =
  if (m &gt; n) then
    raise (new System.Exception(&quot;The modulus is too small to encrypt the message&quot;))
  else
    modulo_power m e n

// A decrypted message is m = c^d [mod n]
let decrypt c d n =
  modulo_power c d n

// RSA example.
let p = 61
let q = 53
let n = p * q
let e = 17
let d = private_exponent e p q
let message = 123
let c = encrypt message e n
let m = decrypt c d n
</pre>
<p>I think the code presented is self-explainatory and each function is briefly described in the comments, but there is a strange thing that you may have noticed.</p>
<p>The first function I defined is the <em>modulus</em> operator, but F# already has a <em>modulus</em> operator, so why bothering?</p>
<p>Before writing that function I was about to getting crazy, since everything else was already written but the encryption was not working properly. I debugged and tested again and again and eventually I found out that sometimes the result of the native modulo operation was a negative number.</p>
<p>After a short lookup on Wikipedia, I discovered that <a href="http://en.wikipedia.org/wiki/Modulo_operation">each programming language implements the modulo operator differently</a> and while in Scheme the result has the same sign as the divisor, in F# the sign of the result is the same as the dividend!</p>

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.claudiocherubino.it/2008/12/28/random-testing-in-f-with-fscheck/" title="Random testing in F# with FsCheck (28 December 2008)">Random testing in F# with FsCheck</a> (2)</li>
	<li><a href="http://www.claudiocherubino.it/2008/02/08/project-euler-in-f-problem-5-alternative-solution/" title="Project Euler in F# &#8211; Problem 5 (alternative solution) (8 February 2008)">Project Euler in F# &#8211; Problem 5 (alternative solution)</a> (4)</li>
	<li><a href="http://www.claudiocherubino.it/2009/04/15/luhn-algorithm-in-f/" title="Luhn algorithm in F# (15 April 2009)">Luhn algorithm in F#</a> (1)</li>
	<li><a href="http://www.claudiocherubino.it/2008/07/01/the-missing-number/" title="The missing number (1 July 2008)">The missing number</a> (13)</li>
	<li><a href="http://www.claudiocherubino.it/2008/02/20/the-2008-winter-scripting-games-pairing-off/" title="The 2008 Winter Scripting Games: Pairing Off (20 February 2008)">The 2008 Winter Scripting Games: Pairing Off</a> (2)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.claudiocherubino.it/2008/12/01/implementation-of-rsa-in-f/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>F# September CTP released!</title>
		<link>http://www.claudiocherubino.it/2008/08/31/f-september-ctp-released/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=f-september-ctp-released</link>
		<comments>http://www.claudiocherubino.it/2008/08/31/f-september-ctp-released/#comments</comments>
		<pubDate>Sun, 31 Aug 2008 10:01:27 +0000</pubDate>
		<dc:creator>claudio</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[ctp]]></category>
		<category><![CDATA[don syme]]></category>
		<category><![CDATA[f#]]></category>
		<category><![CDATA[f# developer center]]></category>

		<guid isPermaLink="false">http://www.claudiocherubino.it/?p=44</guid>
		<description><![CDATA[F# development has finally reached CTP (Community Technology Preview) release and this actually makes F# a first-class citizen in the .Net ecosystem. Don Syme himself made this important announcement on his blog, where he describes some of the major improvements, that include new and improved F# Project system and language service. The detailed release notes [...]]]></description>
			<content:encoded><![CDATA[<p>F# development has finally reached <strong>CTP</strong> (<strong>Community Technology Preview</strong>) release and this actually makes F# a first-class citizen in the .Net ecosystem.</p>
<p><strong>Don Syme</strong> himself made <a href="http://blogs.msdn.com/dsyme/archive/2008/08/29/the-f-september-2008-ctp-is-now-available.aspx">this important announcement</a> on his blog, where he describes some of the major improvements, that include new and improved <strong>F# Project system</strong> and language service.</p>
<p>The detailed release notes can be found <a href="http://blogs.msdn.com/dsyme/archive/2008/08/29/detailed-release-notes-for-the-f-september-2008-ctp-release.aspx">here</a>, while the installer can be downloaded from the brand new <a href="http://msdn.microsoft.com/en-gb/fsharp/default.aspx"><strong>Microsoft F# Developer Center</strong></a>.</p>

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.claudiocherubino.it/2008/07/01/the-missing-number/" title="The missing number (1 July 2008)">The missing number</a> (13)</li>
	<li><a href="http://www.claudiocherubino.it/2008/02/20/the-2008-winter-scripting-games-pairing-off/" title="The 2008 Winter Scripting Games: Pairing Off (20 February 2008)">The 2008 Winter Scripting Games: Pairing Off</a> (2)</li>
	<li><a href="http://www.claudiocherubino.it/2010/01/25/spell-checking-with-f/" title="Spell checking with F# (25 January 2010)">Spell checking with F#</a> (0)</li>
	<li><a href="http://www.claudiocherubino.it/2008/01/22/sorting-odd-and-even-numbers-in-f/" title="Sorting odd and even numbers in F# (22 January 2008)">Sorting odd and even numbers in F#</a> (5)</li>
	<li><a href="http://www.claudiocherubino.it/2008/03/07/run-length-encoding-in-f/" title="Run-Length Encoding in F# (7 March 2008)">Run-Length Encoding in F#</a> (2)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.claudiocherubino.it/2008/08/31/f-september-ctp-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
