F# Project Euler Problem 2

Solving second problem for Project Euler Problem 2 is an interesting one.

Each new term in the Fibonacci sequence is generated by
adding the previous two terms. By starting with 1 and 2, the first
10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
By considering the terms in the Fibonacci sequence whose
values do not exceed four million, find the sum of the even
valued terms.

Challenge here is to generate a fibonacci sequence, which is the fib(n-1) + fib(n-2) formula. This generates a evaluation tree during recursion and becomes quite large when generating a large N fibonacci value, and stackoverflow happens. To tackle this problem in a more efficient way, we shouldn’t generate the number for N re-cursing backwards, but generate the number from summation forwards.

Here’s my first F# solution I came up with.

let initiniteFib =
    let rec fib1 n1 n2 =
        seq {
            yield n1
            yield! fib1 n2 (n1+n2)
    fib1 0I 1I

let answer = initiniteFib 
                |> Seq.takeWhile (fun x -> x < 4000000I)
                |> Seq.filter (fun x -> x % 2I = 0I)
                |> Seq.sum

Another way to solve the same problem, is using Seq.unfold.

let answer = Seq.unfold (fun (first, second) -> Some(second, (second, first+second))) (0I, 1I)
                |> Seq.takeWhile (fun x-> x < 4000000I)
                |> Seq.filter (fun x -> x % 2I = 0I)
                |> Seq.sum

If you have more interesting ways to solve this, please share.

F# Project Euler Problem 1

Recently I have started getting more exposure about F# at work. Another developer and myself managed woto build a scheduling service purely written in F#, and it was a very humbling experience.

I’ve gotten much more confidence now writing in F#, and starting to actually enjoy it more than C#. It’s a very different mindset and paradigm to write functionally.

We’ve also started a small community at work learning, sharing and practicing in F#. One of the interesting exercises is solving mathematical problems in F# from Project Euler.

Here’s my solution in solving Problem 1.

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

let answer = seq {1..999}
|> Seq.filter (fun n -> n % 3 = 0 || n % 5 = 0)
|> Seq.sum

Simple enough🙂

RetryTask using Task Parallel Library

Have you ever had to implement some form of retry functionality? I have, a couple of times in fact. Common scenarios would be to retry web service requests in the event of CommunicationException, or retry some time consuming method invocation. The parameters for these retry logic would be to wait a specified amount of time and to retry a specified number of times.

A very common retry logic I’ve seen to implement the retry logic is using a while loop to enforce the maximum number of retries, and a Thread.Sleep to perform the wait time. This is an example below.

Read the rest of this entry »

Posted in C#, EdLib. Tags: . Leave a Comment »

String.Format and IFormatProvider

Have you ever noticed this overload of String.Format(IFormatProvider, String, Object[])? IFormatProvider is actually a very useful interface that allows us to create custom formats to transform our inputs. The IFormatProvider link has examples on how to do it.

This is my version on how to create a custom formatter factory that understand custom formats we create, and routes to the appropriate formatter. If a non-custom format is used, the conversion will still be performed as normal. In the example, I’m trying to create custom formats “bsb” and “acctno” which will convert numbers to a “999-999” format and “1234-56789” format using the CustomFormatProvider.

Read the rest of this entry »

XPath Extensions is cool!

I’m been using XDocument and it’s API for some time, but I wasn’t aware of an XPath Extensions in the .NET Framework. Thanks to my co-worker Lucy, she’s shared with me some good tips and in turn I’m sharing it with you.

Consider this XML.

<?xml version="1.0" encoding="utf-8" ?>
 <Product id="1" name="Nexus 5">
 <Product id="5" name="Wireless Charger">

This would have been typically how I would dig into the XML to find certain data using XDocument, in a safe way of course.

Read the rest of this entry »

Posted in C#. Tags: , . Leave a Comment »

String.Split throws OutOfMemoryException

Recently I’ve been doing a fair bit of memory profiling and fixing memory issues at work. One interesting cause of an OutOfMemoryException I’ve encountered occurred when using String.Split for several large csv files concurrently. Of course the size and number of lines in the file that triggers the OutOfMemoryException is subjected to the memory capacity of your computer. To reproduce this, it’s relatively easy, first you need to create a large csv file.

Here’s some code to do it.

Read the rest of this entry »

Posted in EdLib. Tags: . Leave a Comment »

Object Proxy

Consider this simplistic example, which uses a stream reader.

public class FileLoader
    private readonly StreamReader _streamReader;

    public FileLoader(StreamReader streamReader)
        _streamReader = streamReader;

    public IEnumerable<string> Read()
        var output = new List<string>();
        string line;
        while (!string.IsNullOrEmpty(line = _streamReader.ReadLine()))
        return output;

The problem I have with this class is that it isn’t exactly unit testable. First of all, it uses a stream reader and it’s not straightforward to be able to mock a stream reader due to the lack of an interface. Secondly what I reckon most developers would do is pass a real stream reader into the class and write tests in that fashion, which would be more of an integration test.

Read the rest of this entry »

Posted in EdLib. Tags: . Leave a Comment »

Get every new post delivered to your Inbox.

Join 93 other followers