<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>FSharp.it</title>
	
	<link>http://www.fsharp.it</link>
	<description>Functional programming on .Net</description>
	<lastBuildDate>Thu, 06 May 2010 20:56:04 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/fsharpit" /><feedburner:info uri="fsharpit" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Functional programming interview question</title>
		<link>http://feedproxy.google.com/~r/fsharpit/~3/XsfANQkZlCw/</link>
		<comments>http://www.fsharp.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.fsharp.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.fsharp.it/2008/04/23/remove-duplicate-values-from-a-list-in-f/">filter duplicates</a>, sort and count the elements of the sequences.</p>
<img src="http://feeds.feedburner.com/~r/fsharpit/~4/XsfANQkZlCw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fsharp.it/2009/08/26/functional-programming-interview-question/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.fsharp.it/2009/08/26/functional-programming-interview-question/</feedburner:origLink></item>
		<item>
		<title>F# introductory article on IoProgrammo magazine</title>
		<link>http://feedproxy.google.com/~r/fsharpit/~3/FJHb1hQ2oEw/</link>
		<comments>http://www.fsharp.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[News]]></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.fsharp.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 application, [...]]]></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.fsharp.it/wp-content/uploads/2009/07/ioprogrammo_agosto2009.jpg"><img src="http://www.fsharp.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>
<img src="http://feeds.feedburner.com/~r/fsharpit/~4/FJHb1hQ2oEw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fsharp.it/2009/07/21/f-introductory-article-on-ioprogrammo-magazine/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.fsharp.it/2009/07/21/f-introductory-article-on-ioprogrammo-magazine/</feedburner:origLink></item>
		<item>
		<title>Merging arrays</title>
		<link>http://feedproxy.google.com/~r/fsharpit/~3/OSlp0lV9ubE/</link>
		<comments>http://www.fsharp.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.fsharp.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 O(n) [...]]]></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.fsharp.it/wp-content/uploads/2009/06/MergeArrays.png"><img src="http://www.fsharp.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>
<img src="http://feeds.feedburner.com/~r/fsharpit/~4/OSlp0lV9ubE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fsharp.it/2009/06/13/merging-arrays/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		<feedburner:origLink>http://www.fsharp.it/2009/06/13/merging-arrays/</feedburner:origLink></item>
		<item>
		<title>Project Euler in F# – Problem 28</title>
		<link>http://feedproxy.google.com/~r/fsharpit/~3/Rxq9oxQPDtg/</link>
		<comments>http://www.fsharp.it/2009/05/22/project-euler-in-f-problem-28/#comments</comments>
		<pubDate>Fri, 22 May 2009 15:57:24 +0000</pubDate>
		<dc:creator>claudio</dc:creator>
				<category><![CDATA[Project Euler]]></category>
		<category><![CDATA[accumulator]]></category>
		<category><![CDATA[f#]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[spiral]]></category>
		<category><![CDATA[tail recursion]]></category>

		<guid isPermaLink="false">http://www.fsharp.it/?p=128</guid>
		<description><![CDATA[Sometimes, when I find a problem like Project Euler problem 28, I remember that human beings are smarter than computers.  
Let&#8217;s read the problem statement, it doesn&#8217;t seem easy at first glance:

Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:

21 [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes, when I find a problem like <a href="http://projecteuler.net/index.php?section=problems&#038;id=28">Project Euler problem 28</a>, I remember that human beings are smarter than computers. <img src='http://www.fsharp.it/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Let&#8217;s read the problem statement, it doesn&#8217;t seem easy at first glance:</p>
<blockquote>
<p>Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:</p>
</blockquote>
<p style='text-align:center;font-family:courier new;'><span style='color:#ff0000;font-family:courier new;'>21</span> 22 23 24 <span style='color:#ff0000;font-family:courier new;'>25</span><br />
20 &nbsp;<span style='color:#ff0000;font-family:courier new;'>7</span> &nbsp;8 &nbsp;<span style='color:#ff0000;font-family:courier new;'>9</span> 10<br />
19 &nbsp;6 &nbsp;<span style='color:#ff0000;font-family:courier new;'>1</span> &nbsp;2 11<br />
18 &nbsp;<span style='color:#ff0000;font-family:courier new;'>5</span> &nbsp;4 &nbsp;<span style='color:#ff0000;font-family:courier new;'>3</span> 12<br />
<span style='color:#ff0000;font-family:courier new;'>17</span> 16 15 14 <span style='color:#ff0000;font-family:courier new;'>13</span></p>
<blockquote>
<p>It can be verified that the sum of both diagonals is 101.</p>
<p>What is the sum of both diagonals in a 1001 by 1001 spiral formed in the same way?</p>
</blockquote>
<p>If we don&#8217;t think of anything <em>creative</em>, we are forced to write an algorithm to draw that 1001&#215;1001 number spiral and then sum both diagonals together.</p>
<p>However, we can start noticing that the number in the top-right position is always <em>n</em>^2, where <em>n</em> is the length of one side of the spiral. In the example, the spiral is 5 by 5 and the top-right value is 25. In a 3 by 3 spiral it would be 9, 49 in a 7 by 7 spiral and so on.</p>
<p>If we concentrate on the outer ring of the spiral, then the inner sum can be obtained by recursion, so we only need to find a trick for the top-left, bottom-left and bottom-right numbers.</p>
<p>They are 21, 17 and 13 in a 5&#215;5 spiral, so it seems like they can be computed starting from the top-right number and repeatedly subtracting 4 (i.e. <em>n &#8211; 1</em>). </p>
<p>Let&#8217;s check this theory with the 3&#215;3 spiral: the top-right number is 9, the other corners are 7, 5 and 3. We are indeed subtracting 2 (i.e. <em>n &#8211; 1</em>) each time!</p>
<p>Let&#8217;s summarize: given a <em>n</em> x <em>n</em> spiral we have to sum <em>n^2</em>, <em>n^2 &#8211; (n-1)</em>, <em>n^2 &#8211; 2(n-1)</em> and <em>n^2 &#8211; 3(n-1)</em>.</p>
<p>Some elementary math and we get <em>4n^2 &#8211; 6n + 6</em> for each ring of the spiral.<br />
The base case of the recursion is the 1&#215;1 spiral and in that case the (degenerate) diagonal sum is 1.</p>
<p>Given these premises it is very easy to write the F# code to implement the algorithm:</p>
<pre class="brush: fsharp">
let rec euler28 n =
  match n with
  | 1 -&gt; 1
  | _ -&gt; euler28 (n-2) + (4 * n * n) - (6 * n) + 6
</pre>
<p>An improvement of the code above would be using <em><a href="http://en.wikipedia.org/wiki/Tail_recursion">tail recursion</a></em>, which means that the last operation of the function should be a recursive call. This leads to a reduction of the stack space used from <em>O(n)</em> to <em>O(1)</em> and let us avoid stack overflow exceptions:</p>
<pre class="brush: fsharp">
let tail_euler28 n =
  let rec spiral n sum =
    match n with
    | 1 -&gt; sum + 1
    | _ -&gt; spiral (n - 2) (sum + (4 * n * n) - (6 * n) + 6)
  spiral n 0
</pre>
<p>As it is usually done in <em>tail recursion</em>, we define an <em>accumulator</em> parameter (<em>sum</em> in the example) which is used to store the partial result of the computation, eliminating the need to keep the state on the stack.</p>
<p>In both solutions I&#8217;ve left a bug that can lead to an infinite loop. Can you spot it?</p>
<img src="http://feeds.feedburner.com/~r/fsharpit/~4/Rxq9oxQPDtg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fsharp.it/2009/05/22/project-euler-in-f-problem-28/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://www.fsharp.it/2009/05/22/project-euler-in-f-problem-28/</feedburner:origLink></item>
		<item>
		<title>Luhn algorithm in F#</title>
		<link>http://feedproxy.google.com/~r/fsharpit/~3/4Wt2_vwrnXA/</link>
		<comments>http://www.fsharp.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.fsharp.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 from the rightmost [...]]]></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>
<img src="http://feeds.feedburner.com/~r/fsharpit/~4/4Wt2_vwrnXA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fsharp.it/2009/04/15/luhn-algorithm-in-f/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.fsharp.it/2009/04/15/luhn-algorithm-in-f/</feedburner:origLink></item>
		<item>
		<title>Project Euler in F# – Problem 52</title>
		<link>http://feedproxy.google.com/~r/fsharpit/~3/GmpYvtMVIcw/</link>
		<comments>http://www.fsharp.it/2009/03/20/project-euler-in-f-problem-52/#comments</comments>
		<pubDate>Fri, 20 Mar 2009 16:04:22 +0000</pubDate>
		<dc:creator>claudio</dc:creator>
				<category><![CDATA[Project Euler]]></category>
		<category><![CDATA[digits]]></category>
		<category><![CDATA[f#]]></category>
		<category><![CDATA[fsharp]]></category>
		<category><![CDATA[set]]></category>
		<category><![CDATA[unfold]]></category>

		<guid isPermaLink="false">http://www.fsharp.it/?p=116</guid>
		<description><![CDATA[After a long break, let&#8217;s resume with the Project Euler series.
The next one to be solved is Problem 52:

It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the [...]]]></description>
			<content:encoded><![CDATA[<p>After a long break, let&#8217;s resume with the <strong>Project Euler</strong> series.</p>
<p>The next one to be solved is <a href="http://projecteuler.net/index.php?section=problems&#038;id=52">Problem 52</a>:</p>
<blockquote><p>
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.</p>
<p>Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
</p></blockquote>
<p>As usual, we have to break the problem into small pieces and solve these pieces one by one.</p>
<p>As in many other Project Euler problems we have to extract the digits of a number, and this is done by converting the number into a string (i.e. an array of characters) and then casting the characters to integers.</p>
<p>We also need a function to check if two numbers are made of the same digits. For each number we create a set from the sequence of its digits, in order to ignore the order of the items and discard duplicates. Then we apply the standard set comparison operator to get the result.</p>
<p>We have to multiply each positive integer by 2, 3, 4, 5 and 6, so we can define the <em>multiples</em> function, which takes an integer <em>x</em> and returns a list containing five elements, corresponding to <em>2x</em>, <em>3x</em>, <em>4x</em>, <em>5x</em> and <em>6x</em>.</p>
<p>Thanks to these three functions, checking if a number and its multiples contain exactly the same digits is very easy. In fact, we generate the list of multiples and test all of them with the <em>same_digits</em> function.</p>
<p>The algorithm to get the answer to the problem is the following: generate an infinite list of integers (remember <em>seq_unfold</em>?), test each number with the <em>check</em> function and return the first value that passes the test.</p>
<pre class="brush: fsharp">
#light

let digits n =
  n.ToString() |&gt; Seq.map (string &gt;&gt; int)

let same_digits a b =
  Set.equal (Set.of_seq (digits a)) (Set.of_seq (digits b))

let multiples n =
  [2 .. 6] |&gt; Seq.map (fun x -&gt; n * x)

let check n =
  n |&gt; multiples |&gt; Seq.for_all (same_digits n)

let answer =
  1 |&gt; Seq.unfold (fun i -&gt; Some (i, i + 1)) |&gt; Seq.first (fun x -&gt; if check x then Some (x) else None)
</pre>
<p>There is also a well-known (and tricky) solution for this problem, which was presented in the book &#8220;<em>The man who calculated</em>&#8220;. Did you know it?</p>
<img src="http://feeds.feedburner.com/~r/fsharpit/~4/GmpYvtMVIcw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fsharp.it/2009/03/20/project-euler-in-f-problem-52/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://www.fsharp.it/2009/03/20/project-euler-in-f-problem-52/</feedburner:origLink></item>
		<item>
		<title>Brainfuck interpreter in F#</title>
		<link>http://feedproxy.google.com/~r/fsharpit/~3/vEchzIDjSuc/</link>
		<comments>http://www.fsharp.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.fsharp.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 a data [...]]]></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
  | &#039;]&#039; -&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
  | &#039;[&#039; -&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
  | &#039;+&#039; -&gt; { program = state.program ; memory = setMem state (getMem state + 1) ; pc = state.pc + 1 ; pos = state.pos }
  | &#039;-&#039; -&gt; { program = state.program ; memory = setMem state (getMem state &#8211; 1) ; pc = state.pc + 1 ; pos = state.pos }
  | &#039;&lt;&#039; -&gt; { program = state.program ; memory = state.memory ; pc = state.pc + 1 ; pos = state.pos &#8211; 1}
  | &#039;&gt;&#039; -&gt; { program = state.program ; memory = state.memory ; pc = state.pc + 1 ; pos = state.pos + 1}
  | &#039;[&#039; -&gt; if (state.memory.[state.pos] = 0) then moveToForwardMatch state else nextCommand state
  | &#039;]&#039; -&gt; if (state.memory.[state.pos] &lt;&gt; 0) then moveToPreviousMatch state else nextCommand state
  | &#039;.&#039; -&gt; outputByte state
  | &#039;,&#039; -&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
  | &#039;]&#039; -&gt; (nextCommand state)
  | _ -&gt; moveToForwardMatch (nextCommand state)

let rec moveToPreviousMatch (state : BFState) =
  match state.program.[state.pc] with
  | &#039;[&#039; -&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
  | &#039;+&#039; -&gt; { program = state.program ; memory = setMem state (getMem state + 1) ; pc = state.pc + 1 ; pos = state.pos }
  | &#039;-&#039; -&gt; { program = state.program ; memory = setMem state (getMem state - 1) ; pc = state.pc + 1 ; pos = state.pos }
  | &#039;&lt;&#039; -&gt; { program = state.program ; memory = state.memory ; pc = state.pc + 1 ; pos = state.pos - 1}
  | &#039;&gt;&#039; -&gt; { program = state.program ; memory = state.memory ; pc = state.pc + 1 ; pos = state.pos + 1}
  | &#039;[&#039; -&gt; if (state.memory.[state.pos] = 0) then moveToForwardMatch state else nextCommand state
  | &#039;]&#039; -&gt; if (state.memory.[state.pos] &lt;&gt; 0) then moveToPreviousMatch state else nextCommand state
  | &#039;.&#039; -&gt; outputByte state
  | &#039;,&#039; -&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>
<img src="http://feeds.feedburner.com/~r/fsharpit/~4/vEchzIDjSuc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fsharp.it/2009/02/12/brainfuck-interpreter-in-f/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.fsharp.it/2009/02/12/brainfuck-interpreter-in-f/</feedburner:origLink></item>
		<item>
		<title>Facebook FizzBuzz</title>
		<link>http://feedproxy.google.com/~r/fsharpit/~3/uUnDBW1XJog/</link>
		<comments>http://www.fsharp.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.fsharp.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 more than [...]]]></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.fsharp.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>
<img src="http://feeds.feedburner.com/~r/fsharpit/~4/uUnDBW1XJog" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fsharp.it/2009/01/23/facebook-fizzbuzz/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://www.fsharp.it/2009/01/23/facebook-fizzbuzz/</feedburner:origLink></item>
		<item>
		<title>Random testing in F# with FsCheck</title>
		<link>http://feedproxy.google.com/~r/fsharpit/~3/wAlhnYEfkeA/</link>
		<comments>http://www.fsharp.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.fsharp.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 library generates [...]]]></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.fsharp.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.fsharp.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.fsharp.it/wp-content/uploads/2008/12/fscheck_passedtests.png"><img src="http://www.fsharp.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.fsharp.it/wp-content/uploads/2008/12/fschecktest.zip'>here</a>.</p>
<img src="http://feeds.feedburner.com/~r/fsharpit/~4/wAlhnYEfkeA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fsharp.it/2008/12/28/random-testing-in-f-with-fscheck/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.fsharp.it/2008/12/28/random-testing-in-f-with-fscheck/</feedburner:origLink></item>
		<item>
		<title>Project Euler in F# – Problem 55</title>
		<link>http://feedproxy.google.com/~r/fsharpit/~3/sVriIeZsuvQ/</link>
		<comments>http://www.fsharp.it/2008/12/17/project-euler-in-f-problem-55/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 17:30:10 +0000</pubDate>
		<dc:creator>claudio</dc:creator>
				<category><![CDATA[Project Euler]]></category>
		<category><![CDATA[f#]]></category>
		<category><![CDATA[fsharp]]></category>
		<category><![CDATA[Lychrel]]></category>
		<category><![CDATA[palindromic]]></category>
		<category><![CDATA[palindromic number]]></category>

		<guid isPermaLink="false">http://www.fsharp.it/?p=78</guid>
		<description><![CDATA[As in the last post, in the description of Project Euler problem 55 there is a detailed step-by-step solution of the problem itself and we just have to write the F# code to perform the tasks.
The only thing that I really had to understand is the definition of Lychrel numbers:

If we take 47, reverse and [...]]]></description>
			<content:encoded><![CDATA[<p>As in the <a href="http://www.fsharp.it/2008/12/07/project-euler-in-f-problem-53/">last post</a>, in the description of <a href="http://projecteuler.net/index.php?section=problems&#038;id=55">Project Euler problem 55</a> there is a detailed step-by-step solution of the problem itself and we just have to write the F# code to perform the tasks.</p>
<p>The only thing that I really had to understand is the definition of <em>Lychrel numbers</em>:</p>
<blockquote><p>
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.</p>
<p>Not all numbers produce palindromes so quickly. For example,</p>
<p>349 + 943 = 1292,<br />
1292 + 2921 = 4213<br />
4213 + 3124 = 7337</p>
<p>That is, 349 took three iterations to arrive at a palindrome.</p>
<p>Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits).</p>
<p>Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994.</p>
<p>How many Lychrel numbers are there below ten-thousand?
</p></blockquote>
<p>As usual, it is suggested to break down the problem into little pieces that can be easily solved with a few lines of code each.</p>
<p>First, we need a function to reverse an integer and another one to check whether a number is palindromic, i.e. it is equal to its reverse.</p>
<p>Then we define a function that will be used during each iteration to take a number and sum it with its reverse. This new number is the one that will be checked next for being a palindrome inside the <em>isLychrel</em> function.</p>
<p>If we found a palindrome then the number under testing is not a <em>Lychrel</em>, otherwise we can start the next iteration up to a maximum of 50 times. If we hit this limit then we can conclude the number is a <em>Lychrel</em>.</p>
<p>We have now all the pieces required to answer the original question. Just take all numbers smaller then 10000, filter the <em>Lychrel</em> ones and count them:</p>
<pre class="brush: fsharp">
#light

let reverse n =
  n.ToString().ToCharArray()
  |&gt; Array.rev
  |&gt; Array.map (fun x -&gt; x.ToString())
  |&gt; Array.reduce_left (^)
  |&gt; bigint.Parse

let isPalindromic n =
  n = reverse n 

let reverseAndAdd n =
  n + reverse n   

let isLychrel n =
  let rec isLychrelIter n i =
    match i with
    | 50 -&gt; true
    | _ -&gt;
      let r = reverseAndAdd n
      if isPalindromic r then
        false
      else
        isLychrelIter r (i+1)
  isLychrelIter n 1

let answer = [1I .. 10000I]
             |&gt; Seq.filter (fun x -&gt; isLychrel x)
             |&gt; Seq.length
</pre>
<img src="http://feeds.feedburner.com/~r/fsharpit/~4/sVriIeZsuvQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fsharp.it/2008/12/17/project-euler-in-f-problem-55/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.fsharp.it/2008/12/17/project-euler-in-f-problem-55/</feedburner:origLink></item>
	</channel>
</rss>

