Search

Categories

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Send mail to the author(s) E-mail

# Friday, 09 October 2015

The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?

// Prime number generator - it can only divide by itself and 1 let primes = [for i in [3..2..7000] do let divisors = [3..2..i/2-1] let mutable isPrime = true for j in divisors do if i % j = 0 then isPrime <- false if isPrime then yield i] // largest prime factor.. notice I on the end to denote a bigint let num = 600851475143I for i in primes do if num % (bigint(i)) = 0I then printfn "%i is a factor" i // 6857

converting an int to a bigint was tricky to find.  As only  then could I divide a bigint by a bigint to check if it was a prime factor.

Note 7000.. could go up to int64 (sqrt(double num)).. but this takes a lot of time.

Functional Style
Much faster, and using sequences instead of a list above:

let maximumPossibleDivisor n = int64 (sqrt(double(n))) let factorsOf n = [3L..2L..maximumPossibleDivisor(n)] |> Seq.filter (fun x -> n % x = 0L) let isPrime n = factorsOf(n) |> Seq.length = 0 let findMaxPrimeFactorOf n = [3L..2L..maximumPossibleDivisor(n)] |> Seq.filter (fun x -> n % x = 0L) |> Seq.filter isPrime |> Seq.max let maxPrime = findMaxPrimeFactorOf(600851475143L) printfn "%A" maxPrime

Explanation

  • We only need to check up to the Sqrt of maxPrime for it’s prime factors eg for 13195, the sqrt is 114
  • Get a sequence of factors eg 3,5,7,9..113
  • IsPrime n… checks to see if any 13195 is divisible by any of the sequence above
| | # 
# Wednesday, 07 October 2015
( c# | Euler | Euler Functional | F# )

https://projecteuler.net/archives  is a fantastic list of puzzles which are solvable by programming.

I find them excellent for exploring into a language.

https://github.com/djhmateer/Euler

Strategy is to explore F#, then see how in C# it can be written

Problem1

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.

F#

// Solution5 - List.filter let total' = [1..999] // filter on a function (predicate) |> List.filter(fun i -> i % 5 = 0 || i % 3 = 0) |> List.sum printfn "result %i" total

C#

// Solution 1 - Iterative approach int sum = 0; for (int i = 1; i < 1000; i++) { if (i % 3 == 0 || i % 5 == 0) sum += i; } Console.WriteLine(sum); // Solution 2 - F# inspired solution - using Enumerable var result = Enumerable.Range(1, 999).Where(x => x % 3 == 0 || x % 5 == 0).Sum(); Console.WriteLine(result);
| | # 
# Tuesday, 06 October 2015
# Friday, 25 September 2015
( F# )

Using F# library with MVC – this could be interesting and have got ASP.NET5

image

Okay, I think I’ll stick with MVC4 for now!

Creating an ‘Empty Web Project’, so not WebAPI, nor a SPA

Ended up going back to VS2013 to make things easier (VS2015 has limited tooling support for MVC4), and I couldn’t get the example to compile.  Model issues in the view.

VS2013

image
2 F# projects
C# view referencing F# Enum types

image
Custom F# validator to make sure the correct Enum

image

So have a web app largely working in F#!

| | # 
( F# )

// Classes in F#! // () no parameters.. for the ctor of the class // x is this, or self.. could be anything type Car() = member x.Move() = printfn "The car is moving" // dont need new.. // only need new if implements IDisposable let car = Car() car.Move()

mkore

// Classes in F#! // () no parameters.. for the ctor of the class // x is this, or self.. could be anything type Car(color: string, wheelCount: int) = do if wheelCount < 3 then failwith "Three wheels at least" if wheelCount > 99 then failwith "That's ridiculous" // secondary ctor new() = Car("red", 4) member x.Move() = printfn "The %s car is moving" color // dont need new.. // only need new if implements IDisposable let car = Car() car.Move() let greenCar = Car("green", 100) greenCar.Move()

and

// standard .NET enum type type CarType = | Tricar = 0 | StandardFourWheeler = 1 | HeavyLoadCarrier = 2 | ReallyLargeTruck = 3 | CrazyHugeMythicalMonser = 4 | WeirdContraption = 5 // Classes in F#! // () no parameters.. for the ctor of the class // x is this, or self.. could be anything type Car(color: string, wheelCount: int) = do if wheelCount < 3 then failwith "Three wheels at least" if wheelCount > 99 then failwith "That's ridiculous" let carType = // Switch can't do this (be assigned to a value) match wheelCount with | 3 -> CarType.Tricar | 4 -> CarType.StandardFourWheeler | 6 -> CarType.HeavyLoadCarrier | x when x % 2 = 1 -> CarType.WeirdContraption | _ -> CarType.CrazyHugeMythicalMonser // secondary ctor new() = Car("red", 4) // %A is Any.. convert CarType to a .ToString() member x.Move() = printfn "The %s car (%A) is moving" color carType // dont need new.. // only need new if implements IDisposable let car = Car() car.Move() let greenCar = Car("green", 3) greenCar.Move()

Mutable Properties

// standard .NET enum type type CarType = | Tricar = 0 | StandardFourWheeler = 1 | HeavyLoadCarrier = 2 | ReallyLargeTruck = 3 | CrazyHugeMythicalMonser = 4 | WeirdContraption = 5 // Classes in F#! // () no parameters.. for the ctor of the class // x is this, or self.. could be anything type Car(color: string, wheelCount: int) = do if wheelCount < 3 then failwith "Three wheels at least" if wheelCount > 99 then failwith "That's ridiculous" let carType = // Switch can't do this (be assigned to a value) match wheelCount with | 3 -> CarType.Tricar | 4 -> CarType.StandardFourWheeler | 6 -> CarType.HeavyLoadCarrier | x when x % 2 = 1 -> CarType.WeirdContraption | _ -> CarType.CrazyHugeMythicalMonser let mutable passengerCount = 0 // secondary ctor new() = Car("red", 4) // %A is Any.. convert CarType to a .ToString() member x.Move() = printfn "The %s car (%A) is moving" color carType // Publishes carType as a property on the class member x.CarType = carType // Prop with a getter and setter member x.PassengerCount with get() = passengerCount // setter has a parameter v (value) // which modifies the mutable value and set v = passengerCount <- v // dont need new.. // only need new if implements IDisposable let car = Car() car.Move() let greenCar = Car("green", 3) greenCar.Move() printfn "green car has type %A" greenCar.CarType printfn "car has %d passengers " car.PassengerCount car.PassengerCount <- 2 printfn "car has %d passengers " car.PassengerCount

TypeAnnotations

image
A good sample project with simple testing

| | # 
# Thursday, 24 September 2015
( F# | Xunit )

Referencing Calculator.add

image

module Calculator let square x = x * x let add x y = x + y let mult x y = x * y

and then

//module Program // Declaring myself in the same namespace // so don't need to do an open module Mateer.Demo.Calculator.Program // open namespace //open Mateer.Demo.Calculator // open the module! //open Mateer.Demo.Calculator.Adder [<EntryPoint>] let main args = printfn "add 5 and 3 is %d" (Adder.add 5 3) 0

and

// specific //namespace global namespace Mateer.Demo.Calculator // need an = and indents when multiple modules in 1 file module Adder = let square x = x * x let add x y = x + y module Multiplier = let mult x y = x * y

Testing

image

xunit2 added via nuget.  TestDriven.Net as the test runner.

| | # 
( F# )

From http://www.pluralsight.com/courses/fsintro

printfn "Hello World!" printfn "How are you today?" // reponse is a value of type string let response = System.Console.ReadLine() // reponse is the argument // %s string, %d decimal, %i int printfn "Great to hear you're %s" response

WinForms:

open System.Windows.Forms let x = 42 printfn "x is %i" x // Record type Person = {Name: string; Age: int} // Person array let testData = [| { Name = "Harry"; Age = 37 }; { Name = "Julie"; Age = 41 }; { Name = "Dave"; Age = 42 } |] // Can pass parameters even though Form doesn't take any // just passes this to a setter let form = new Form(Text = "F# Windows Form") let dataGrid = new DataGridView(Dock=DockStyle.Fill, DataSource = testData) form.Controls.Add(dataGrid) Application.Run(form)

WPF:

open System open System.Windows open System.Windows.Controls // Empty parameter list for this helper function let loadWindow() = // look in HelloWorldWPF assembly let resourceLocator = new Uri("/HelloWorldWPF;component/MainWindow.xaml", UriKind.Relative) // type cast it to Window let window = Application.LoadComponent(resourceLocator) :?> Window // cast clickButton to a Button (window.FindName("clickButton") :?> Button).Click.Add( // add lambda expression/delegate as an event handler // _ no parameters not interested // in F# cannot ignore return values of fn.. // MessageBox.Show returns a value of type MessageBoxResult // so pipe to a helper function in F# ignore fun _ -> MessageBox.Show("Hello World!") |> ignore) // return the window.. the last value that is evaluated is the return window // Get code running in correct threading model [<STAThread>] (new Application()).Run(loadWindow()) |> ignore
| | # 
# Monday, 21 September 2015
( F# )

Going back to the start with F#

FSI – F# Interactive

let SayHello() = printfn "Hello" [<EntryPoint>] let main argv = SayHello() System.Console.ReadKey() |> ignore 0

image

Execute in interactive – alt enter (and R# knew not to run!)
System.DateTime.Now;;
System.DateTime.Now.ToShortTimeString();;

Values, Functions and Flow of Control

> let SayHiTo me =
    printfn "Hi %s" me;;

| | # 
# Thursday, 15 August 2013
( Euler | F# )
let isPyTriplet a b c =
    (a*a) + (b*b) = (c*c)

for a in 1..999 do
    for b in 1..999 do
        let c = 1000-a-b
        if isPyTriplet a b c then
            if(a+b+c = 1000) then
                printfn "%i %i %i" a b c

[<Fact>]
let isPyTriplet_given345_true() = Assert.True(isPyTriplet 3 4 5)

[<Fact>]
let isPyTriplet_given346_() = Assert.False(isPyTriplet 3 4 6)

[<Fact>]
let isPyTriplet_given123_() = Assert.False(isPyTriplet 1 2 3)

Imperative style

// Make a sequence of tuples
let tripletsSum1000 =
                        seq {
                        for a in 1 .. 333 do
                            for b in a + 1 .. 499 do
                                let c = 1000 - b - a
                                if a < b && b < c then
                                     yield (a,b,c)
                         }

// Find from this sequence one that is Pythagorean and return the product
let problem009 =
     tripletsSum1000
     |> Seq.find (fun (a,b,c) -> a * a + b * b = c * c)
     |> fun (a,b,c) -> a*b*c

printfn "%A" problem009

http://infsharpmajor.wordpress.com/2011/10/12/project-euler-problem-9/

| | # 
# Tuesday, 13 August 2013
( Euler | F# )
let xstr:string = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
let chars = xstr.ToCharArray()

let product5startingat x chars =
    let mutable count = 1
    for i in x..x+4 do
        let value = Array.sub chars i 1
        let valueint = int(new string(value))
        count <- count * valueint
    count

let mutable largest = 0
for i in 0..995 do
    let result = product5startingat i chars
    if(result > largest) then
        largest <- result

printfn "%i" largest

An imperative style

let str = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"

// Converts string into a sequence of digits
let digits =
    Seq.map (fun x -> int (System.Char.GetNumericValue x)) str

// Takes every subsequent 5 digits - Seq.windowed.  Multiply them together Seq.reduce applied to each element in the sequence with Seq.map
// then find the maximum with Seq.max
// seq.windowed turns 1000 element list into 996 arrays of subsequences of consecutive digits
let maxproduct num list =
    Seq.max (Seq.map (fun x -> Seq.reduce (*) x) (Seq.windowed num list))

let a = maxproduct 5 digits
printfn "%i" a

Functional from http://blog.asymptotic.co.uk/2009/12/project-euler-in-f-problem-8/

| | # 
# Monday, 12 August 2013
( Euler | F# )
let isPrime x =
    if (x = 2) then
        true
    elif (x%2 = 0) then
        false
    else
        let rec loop i max =
            // This is a prime
            if i >= (max/2) then
            //if i >= int((sqrt(float max))) then
                true
            // Is it divisible by any other other
            elif max%i = 0 then
                false
            else
                loop (i+1) max
        loop 3 x

let getxthPrime numberPrimesToFind =
    let mutable counterOfPrimesFound = 0
    let mutable numberToTry = 2
    while (counterOfPrimesFound < numberPrimesToFind) do
        if (isPrime numberToTry) then
            counterOfPrimesFound <- counterOfPrimesFound + 1
        numberToTry <- numberToTry + 1
    numberToTry-1

printfn "%i" (getxthPrime 10001)

[<Fact>]
let getxthPrime_given6_13() = Assert.Equal(13, getxthPrime 6)


[<Fact>]
let isPrime_given2_true() = Assert.True(isPrime 2)
[<Fact>]
let isPrime_given3_true() = Assert.True(isPrime 3)
[<Fact>]
let isPrime_given4_false() = Assert.False(isPrime 4)
[<Fact>]
let isPrime_given5_true() = Assert.True(isPrime 5)
[<Fact>]
let isPrime_given6_fal() = Assert.False(isPrime 6)
[<Fact>]
let isPrime_given7_true() = Assert.True(isPrime 7)
[<Fact>]
let isPrime_given8_false() = Assert.False(isPrime 8)
[<Fact>]
let isPrime_given9_false() = Assert.False(isPrime 9)
[<Fact>]
let isPrime_given13_true() = Assert.True(isPrime 13)
[<Fact>]
let isPrime_given15_fal() = Assert.False(isPrime 15)

Checks up to maxvalue/2.

let isPrime x =
    if (x = 2) then
        true
    elif (x%2 = 0) then
        false
    else
        let maxI = int(sqrt(float x))+1

        let rec notDivisible i =
            if i > maxI then
                true
            elif x%i = 0 then
                false
            else
                notDivisible (i+2)

        notDivisible 3

Checks up to the squareroot.

let isPrime n = {2L .. n |> float |> sqrt |> int64}
                |> Seq.forall(fun i -> n%i <> 0L)

let primes = seq {1L .. System.Int64.MaxValue}
                |> Seq.filter(isPrime)

let ans = Seq.nth 10001 primes

printfn "%i" ans

Using sequences

Links to other slns: http://breadthfirst.wordpress.com/2010/06/18/project-euler-problem-7/ and http://diditwith.net/2009/01/20/YAPESProblemSevenPart2.aspx

| | # 
# Saturday, 10 August 2013
( Euler | F# )

let sumOfSquares x = [1 .. x] |> Seq.sumBy(fun i -> i*i)

let squared x = x * x

let squareOfSum x = [1 .. x] |> Seq.sum |> squared

let diff = squareOfSum 100 - sumOfSquares 100

printf "diff: %i " diff


[<Fact>]
let sumOfSqaures_given10_385() = Assert.Equal(385, sumOfSquares 10)

[<Fact>]
let squareOfSum_given10_3025() = Assert.Equal(3025, squareOfSum 10)

Sequences are great.. makes it very easy to not have to do loops.

Forward Pipe – a parameter preceding the function name is piped to the function.

let squareOfSum x = [1 .. x] |> Seq.sum |> fun i -> i * i
| | # 
( Euler | F# )

// x is input, max is number to count up to eg 10
let div1To x max =
    let rec loop i =
        if i > max then
            true
        elif x%i <> 0 then
            false
        else
            loop (i+1)
    loop 1

// Smallest number divisible by all numbers from 1 to 20?
let rec loop i =
    if (div1To i 20) then
        printfn "%i" i
    else
        loop (i+1)
loop 1


[<Fact>]
let div1To10_given2520_true() = Assert.True(div1To 2520 10)

[<Fact>]
let div1To10_given2521_false() = Assert.False(div1To 2521 10)

First time used recursive functions in a very ‘for loop’ manner

let a = List.map (fun i -> 2520.0 / i) [1.0 .. 10.0]
printfn "%A" a

And here is a handy function which prints out the results of 2520.0/i a sanity check really.

| | # 
# Friday, 09 August 2013
( Euler | F# )

First shot

let isPalindrome x =
        let xString = x.ToString()
        let a = xString.ToCharArray()

        let len = a.Length
        let halflen = len/2

        let mutable result = true
       
        for i in 1 .. halflen do
            // Left hand side
            let lhsb = Array.sub a (i-1) 1
            let lhss = new string(lhsb)

            // Right hand side
            let rhsb = Array.sub a (len-i) 1
            let rhss = new string(rhsb)

            if (lhss <> rhss) then
                  result <- false
        result

let mutable largest = 0
for i in 100..999 do
    for k in 100..999 do
        let num = i * k
        if (isPalindrome num) then
            if (num > largest) then
                largest <- num
printfn "%i" largest

Charles’s solution in VBScript

'Eulers Challenge Thingy
'Palindromic factoring
'Find the largest palindrome made from the product of two 3-digit numbers
Option Explicit
Dim palintriple
Dim palinreverse
Dim palinsextuple
Dim firstfactor
Dim sndfactor

'Calculate the Six Digit Palindromic Number First
For palintriple = 999 to 100 Step -1
  ' Reverse eg 789 goes to 987
  palinreverse = StrReverse(palintriple)
  ' eg 789*1000=789,000+987= 789,987
  palinsextuple = (palintriple*1000)+palinreverse
  
    'Now Divide by all of the potential factors
    firstfactor = 999
    Do
     sndfactor = palinsextuple/firstfactor
         If sndfactor = 993 Then wscript.echo "missed it!!!!!"
      If CLng(sndfactor) = sndfactor Then
         If sndfactor < 1000 then
          wscript.echo "Highest Palindromic Number = " & palinsextuple
          wscript.echo "First Three digit factor is " & firstfactor
          wscript.echo "Second Three digit factor is " & sndfactor
          wscript.quit 1
         End If
       End If
      firstfactor=firstfactor-1
    Loop Until firstfactor = 100
Next

James’s Solution

let isPalindrome (x:int) =
    let xString=x.ToString()
    let xLen=xString.Length
    let mutable isPal = true
    for i=0 to xString.Length-1 do
        if (xString.[i]<>xString.[xLen-i-1] ) then
            isPal<-false
    
    isPal

let mutable (sumVals : int)=999+999 //start with highest pairs
let mutable (minVals : int)=100+100 //smallest possible pair for the solution
let mutable (y : int)=0
let mutable (maxSolution : int)=0
let mutable (i : int) =0

while (sumVals>minVals) do //loop
    for x = 999 downto (sumVals/2) do
        y<-sumVals-x
        i<-i+1 //get count of iterations to compare with 'Scott Technique'
        if isPalindrome (x*y) then
            if (x*y>maxSolution) then
                maxSolution<-x*y
                minVals<- int (sqrt(float maxSolution))*2
                printfn "new max : %d" maxSolution
                printfn "new smallest sum of pair : %d" minVals
                
    sumVals<-sumVals-1
printfn "Solution2 : %d" maxSolution
printfn "Iterations : %d" i

and factored down:

let isPalindrome (x:int) =  (x/100000 = x%10 && (x/10000)%10 = (x/10)%10 && (x/1000)%10 = (x/100)%10)
let mutable (maxSolution : int)=0
for sumVals=(999+999) downto 200 do for x = 999 downto (sumVals/2) do if (isPalindrome (x*(sumVals-x)) && ((x*(sumVals-x))>maxSolution)) then maxSolution<-x*(sumVals-x)    
printfn "Solution : %d" maxSolution
| | # 
# Thursday, 08 August 2013
( Euler | F# )

The largest prime factor

This proved quite challenging with using bigints in F#

// A number is prime if can only divide by itself and 1.  Can only be odd.
let isPrime x =
    if (x%2L = 0L) then
        false
    else
        let mutable result = true
        for i in 3L..x/2L do
            if (x%i = 0L) then
                result <- false
        result

let lpFactor x =
    let mutable result = int64(1)
    for i in 3L..x/2L do
        if(x%i = 0L) then
            printfn "%i" i
            if (isPrime i) then
                result <- int64(i)
                printfn "primefact %i" i
    result


let a = (lpFactor 600851475143L)

printfn("Hello world")

[<Fact>]
let lpfactor_13195_29() = Assert.Equal(29L, lpFactor 13195L)

//[<Fact>]
//let lpfactor_answer() = Assert.Equal(2L, lpFactor 600851475143L)


[<Fact>]
let isPrime_3_true() = Assert.True(isPrime 3L)

[<Fact>]
let isPrime_4_false() = Assert.False(isPrime 4L)

[<Fact>]
let isPrime_5() = Assert.True(isPrime 5L)

[<Fact>]
let isPrime_7() = Assert.True(isPrime 7L)

[<Fact>]
let isPrime_9() = Assert.False(isPrime 9L)

[<Fact>]
let isPrime_11() = Assert.True(isPrime 11L)

[<Fact>]
let isPrime_13() = Assert.True(isPrime 13L)

[<Fact>]
let isPrime_15() = Assert.False(isPrime 15L)

Refactor1 – Gradbot’s solution using Recursion

let isPrime x =
    // A prime number can't be even
    if (x%2L = 0L) then
        false
    else
        // Check for divisors (other than 1 and itself) up to half the value of the number eg for 15 will check up to 7
        let maxI = x / 2L

        let rec notDivisible i =
            // If we're reached more than the value to check then we are prime
            if i > maxI then
                true
            // Found a divisor so false
            elif x % i = 0L then
                false
            // Add 2 to the 'loop' and call again
            else
                notDivisible (i + 2L)
        
        // Start at 3
        notDivisible 3L

A good first step for getting rid of the mutable state, and using recursion for the ‘loop’

Refactor2 – Sequences

let isPrime x =
    // A prime number can't be even
    if (x%2L = 0L) then
        false
    else
        // Do all elements in the sequence satisfy the predicate?
        Seq.forall (fun i -> x % i <> 0L) { 3L..2L..x/2L }

Very elegant

let isPrime x =
    // A prime number can't be even
    x%2L <> 0L &&
    // Do all elements in the sequence satisfy the predicate?
    Seq.forall (fun i -> x % i <> 0L) { 3L..2L..x/2L }

A single expression where both return a bool.. it does not evaluate the sequence if even.

let isPrime x =
    // Checking even numbers too here
    { 2L..x/2L } |> Seq.forall (fun i -> x % i <> 0L)
    // Same as doing this
    //Seq.forall (fun i -> x % i <> 0L) { 2L..x/2L }

Simplifying but now checking evens

| | # 
# Wednesday, 31 July 2013
( Euler | F# )

First imperative style try at solving the problem.

“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.”

  1. // Euler 2
  2. open Xunit
  3.  
  4. // Fibonnaci - accepts the number in the sequence, and returns the fibonnacci number
  5. let fib x =
  6.     // oldA is directly left starting on the fib3
  7.     // oldB is 2 to the left starting on fib3
  8.     let mutable currentFib, oldA, oldB = 0, 2, 1
  9.  
  10.     // Special case
  11.     if (x = 1) then
  12.         currentFib <- 1
  13.  
  14.     // Special case
  15.     if (x = 2) then
  16.         currentFib <- 2
  17.  
  18.     // Starting at the third
  19.     for i in 3..x do
  20.         currentFib <- oldA + oldB
  21.         // Setting up for next time around loop
  22.         oldB <- oldA
  23.         oldA <- currentFib
  24.     currentFib
  25.  
  26. // Loops and gets the result
  27. let mutable count = 0
  28. for i in 1 .. 32 do
  29.     let x = fib i
  30.     // Evens
  31.     if x%2 = 0 then
  32.         count <- count + x
  33.  
  34. printfn "%i" count
  35.  
  36. // Test the fib function
  37. [<Fact>]
  38. let fib_given1_shouldReturn1() =
  39.     Assert.Equal(1, fib 1)
  40.  
  41. let fib_given2_shouldReturnx() =
  42.     Assert.Equal(2, fib 2)
  43.  
  44. [<Fact>]
  45. let fib_given3_shouldReturnx() =
  46.     Assert.Equal(3, fib 3)
  47.  
  48. [<Fact>]
  49. let fib_given4_shouldReturnx() =
  50.     Assert.Equal(5, fib 4)
  51.  
  52. [<Fact>]
  53. let fib_given5_shouldReturnx() =
  54.     Assert.Equal(8, fib 5)
  55.  
  56. [<Fact>]
  57. let fib_given6_shouldReturnx() =
  58.     Assert.Equal(13, fib 6)

Used asserts at the begging to make sure the algorithm was working for all cases.  Add in xunit from NuGet, and reference from the top of the file using open Xunit.  Then as a test runner I use Resharper and xunit.control.  However testdriven.net looks look too.

**understand the non tail recursive function here:

http://stackoverflow.com/questions/2845744/generating-fibonacci-series-in-f

| | # 
# Monday, 29 July 2013
( Euler | F# )

Here is James’s solution to Euler 2

// rec means a recursive function
let rec fib x y n =
    // returns n if we've reached the end point
    if y>4000000 then n
   
    else if (y%2=0) then fib y (x+y) (n+y)
    else fib y (x+y) n
  
let z= fib 1 2 0

printfn "%i" z

As I’ve avoided (like the plague) recursive functions in the past, I though this would be a great opportunity to start!

“Functional programming relies on recursive functions heavily since imperative looping structures are frowned upon” – from a blog on tail recursion http://blogs.msdn.com/b/chrsmith/archive/2008/08/07/understanding-tail-recursion.aspx

A recursive function is a function which calls itself. eg a factorial function  6! = 6 * 5 * 4 * 3 * 2 * 1 = 720

// Non recursive factorial function - negative
let fact x =
    let mutable product = 1
    //for i in x.. -1 ..1 do
    for i = x downto 1 do
        product <- product * i
    product

from http://en.wikibooks.org/wiki/F_Sharp_Programming/Recursion

fact(6) =
        = 6 * fact(6 - 1)
        = 6 * 5 * fact(5 - 1)
        = 6 * 5 * 4 * fact(4 - 1)
        = 6 * 5 * 4 * 3 * fact(3 - 1)
        = 6 * 5 * 4 * 3 * 2 * fact(2 - 1)
        = 6 * 5 * 4 * 3 * 2 * 1 * fact(1 - 1)
        = 6 * 5 * 4 * 3 * 2 * 1 * 1
        = 720
let rec fact x =
    if x < 1 then 1
    else x * fact (x - 1)

image
Started at 6, then built up the recursive callstack.  Now if I keep debugging it will come up the hierarchy evaluating? as it goes.

image

// can we see the evaluation as it happens by putting in a mutable? ie half way through coming back up the hierarchy what is the total?

let rec fact x =
  if x > 2 then
    x * (fact (x - 1))
  else
    x

I find this easier to read

Tail Recursion

A tail recursive funcion is a special case of recursion in which the last instruction executed in the method is the recursive call… as a result, rail-recursive functions can recursive indefinately without consuming stack space.

image
Notice the Call Stack only has the most recent call on it – it doesn’t need to remember where it is.

let rec count n =
    // 1 million
    if n = 1000000 then
        printfn "done"
    else
        if n % 1000 = 0 then
            printfn "n: %i" n

        count (n + 1) (* recursive call *)

count 0

To make it non tail recursive, put in a () after the count, which would return a unit after every call, thus ensuring that the stack has to be kept.

image

| | # 
# Saturday, 27 July 2013
( F# )
  • %s   string
  • %i   int
  • %f   float
  • %b  bool
  • %A  all?  Pretty printing of tuples, records and union types
  • %0  for all other objects which uses ToString()

Statically typed.

// Making a range (sequence?)
let test =
    [1..10]

// Iterating over the sequence test
for i in test do
    printfn "%d" i

// Iterating over a sequence functionally
let testb =
    [1..10] |> Seq.iter(fun x -> printf "%i " x)

Sequence Iterate…

// or 1 line using Sequence SumBy
let problem1b =
    [1..999] |> Seq.sumBy(fun x -> if (x%3 = 0 || x%5 = 0) then x else 0)
printfn "%i" problem1b

Sequence sumby

| | # 
# Friday, 26 July 2013
( Euler | F# )

First problem solved in F#!!!

Euler1 – “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.”

open Xunit
 
let mul3 x = 
    x % 3 = 0
 
let mul5 x =
    x % 5 = 0
 
let sumOf x =
    let mutable counter = 0
    // loop x times and if is a mul3 or mul5 add to an overall counter
    for i in 1 .. x-1 do
        if mul3 i then
            counter <- counter + i
        else if mul5 i then
            counter <- counter + i
    counter
 
printfn "%d" (sumOf 1000)
 
[<Fact>]
let sumOf_given10_shouldReturn23() = 
    Assert.Equal(23, sumOf 10)
 
[<Fact>]
let sumOf_given16_shouldReturn60() = 
    Assert.Equal(60, sumOf 16)
 
 
[<Fact>]
let multiple3_given3_shouldReturnTrue() = 
    Assert.True(mul3 3)
 
[<Fact>]
let multiple3_given4_shouldReturnFalse() = 
    Assert.False(mul3 4)
 
[<Fact>]
let multiple3_given5_shouldReturnFalse() = 
    Assert.False(mul3 5)
 
[<Fact>]
let multiple3_given6_shouldReturnFalse() = 
    Assert.True(mul3 6)
 
[<Fact>]
let mul5_given3_shouldReturnFalse() = 
    Assert.False(mul5 3)
 
[<Fact>]
let mul5_given5_shouldReturnTrue() = 
    Assert.True(mul5 5)
 
[<Fact>]
let mul5_given15_shouldReturnTrue() = 
    Assert.True(mul5 15)

Issues / Interest I had

  • Getting R# test runner to debug using xunit (Ctrl U L worked to run all tests in solution)
  • Debugger in VS2012 is just like C# for watching locals
  • Is there a more functional way of doing this without mutability

James’s Strategy

I like this idea of having a range, then filtering out.

// James's list of integers from 1 to 999 inclusive, filtered by either x modulus 3 = 0 or x modulus 5 = 0
let eulerList = List.filter (fun x -> (x % 3 * x % 5) = 0 ) [ 1 .. 999 ]  
let eulerSum = eulerList |> List.sum
printfn "Euler Sum: %d" eulerSum


// Daves refactoring pulling out the checking function
let divisibleBy3Or5 x =  x % 3 = 0 || x % 5 = 0
let listOfDivisibleBy3or5 = List.filter(divisibleBy3Or5) [1..999]
printfn "%A" listOfDivisibleBy3or5
// |> forward pipe.  Pipes result of 1 function to another
let eulerSumDave = listOfDivisibleBy3or5 |> List.sum
printfn "%A" eulerSumDave

// Or on 1 line
printfn "Euler Sumx: %d"  ( List.filter (fun x -> (x % 3 = 0 || x % 5 = 0) ) [ 1 .. 999 ]  |> List.sum)

Other Strategies

As I want to learn F# and the functional way (rather than just solving Euler!) I’m going to look at other strategies when I’ve solved the puzzle – I suspect it is going to be interesting.

// or 1 line using Sequence SumBy
let problem1b =
    [1..999] |> Seq.sumBy(fun x -> if (x%3 = 0 || x%5 = 0) then x else 0)
printfn "%i" problem1b
| | # 
# Thursday, 25 July 2013
( F# )

image

Using a custom template

image
C# MVC project, and F# project with controller code in it.

namespace SpeakersFS.MVC.Step1.Models
 
open System.ComponentModel
open System.ComponentModel.DataAnnotations
 
open SpeakersFS
 
// Enum types
type CrossoverType = 
    | Unknown = 0
    | Butterworth = 1
 
type ButterworthOrder = 
    | Unknown = 0
    | First = 1
    | Second = 2
 
// Class with mutable Fields.  Default constructor is ()
type CrossoverCalculationRequest() = 
    let mutable crossoverType = CrossoverType.Unknown
    let mutable butterworthOrder = ButterworthOrder.Unknown
    let mutable crossoverFrequency = 0.0
    let mutable impedance = 0.0
 
    // From DataAnnotations for validation
    [<Required>]
    [<EnumInvalidValue(CrossoverType.Unknown)>]
    [<EnumDataType(typeof<CrossoverType>)>]
    [<DisplayName("Crossover type")>]
    member x.CrossoverType with get() = crossoverType and set v = crossoverType <- v
 
    [<Required>]
    [<EnumInvalidValue(ButterworthOrder.Unknown)>]
    [<EnumDataType(typeof<ButterworthOrder>)>]
    [<DisplayName("Butterworth 'order'")>]
    member x.ButterworthOrder with get() = butterworthOrder and set v = butterworthOrder <- v
 
    [<Required>]
    [<DisplayName("Crossover frequency")>]
    member x.CrossoverFrequency with get() = crossoverFrequency and set v = crossoverFrequency <- v
 
    [<Required>]
    [<DisplayName("Impedance")>]
    member x.Impedance with get() = impedance and set v = impedance <- v
| | # 
( F# )

 

module SpeakerFS.Butterworth
 
// Function signature is float -> float -> float.. 2 float inputs, 1 float return parameter
let firstOrderCapacitance crossoverFrequency impedance = 
    (0.159 / (crossoverFrequency * impedance)) * 1000000.0
 
let firstOrderInductance crossoverFrequency impedance = 
    (impedance / (6.28 * crossoverFrequency)) * 1000.0 
 
let secondOrderCapacitance crossoverFrequency impedance = 
    (0.1125 / (crossoverFrequency * impedance)) * 1000000.0
 
let secondOrderInductance crossoverFrequency impedance = 
    ((impedance * 0.2251) / crossoverFrequency) * 1000.0 

and tests:

module Speakers.ButterworthTests
 
open System
open SpeakerFS
open Xunit
 
// Helper function using type annotations in parameters
let check (expected: float) (actual: float) =
    Assert.Equal(expected, Math.Round(actual,2))
 
module FirstOrder =
    [<Fact>]
    let firstOrderCapacitance_100Hz_80hm() =
        let act = Butterworth.firstOrderCapacitance 100.0 8.0
        check 198.75 act
 
    let firstOrderCapacitance_400Hz_80hm() =
        check 49.69 (Butterworth.firstOrderCapacitance 400.0 8.0)
 
module SecondOrder = 
    [<Fact>]
    let secondOrderCapacitance_100Hz_80hm() =
        check 140.63 (Butterworth.secondOrderCapacitance 100.0 8.0)

image
Ctrl U L to run tests in R# with xunit contrib.

| | # 
# Wednesday, 24 July 2013
( F# )

 

// standard .NET Enum type
type CarType =
    | Tricar = 0
    | StandardFourWheeler = 1
    | HeavyLoadCarrier = 2
    | ReallyLargeTruck = 3
    | CrazyHugeMythical = 4
    | WeirdContraption = 5
   
// Car Class
type Car(colour: string, wheelCount: int) =
    do
        if wheelCount < 3 then 
            failwith "We'll assume that cars must have three wheels at least"
        if wheelCount > 99 then 
            failwith "That's ridiculous"
 
    // A field
    let carType = 
        match wheelCount with
            | 3 -> CarType.Tricar
            | 4 -> CarType.StandardFourWheeler
            | 6 -> CarType.HeavyLoadCarrier
            // An odd number of wheels
            | x when x % 2 = 1 -> CarType.WeirdContraption
            | _ -> CarType.CrazyHugeMythical
 
    let mutable passengerCount = 0;
 
    // Secondary default constructor
    new() = Car("red", 4)
 
    // x is the self reference.. like this.  could be anything.. 
    // %A is Any..makes it ToString()
    member x.Move() = printfn "The %s car (%A) is moving" colour carType
    member x.CarType = carType
    // temp parameter v for value.. assignment operator is <-
    member x.PassengerCount with get() = passengerCount and set v = passengerCount <- v
 
let car = Car()
car.Move()
 
let greenCar = Car("Green",5)
greenCar.Move()
 
// Outputting the readonly property
printfn "green car has type %A" greenCar.CarType
 
printfn "Car has %d passengers on board" car.PassengerCount
 
car.PassengerCount <- 2
printfn "Car has %d passengers on board" car.PassengerCount
 
 
 
| | # 
( F# )

image
Creating a car class in F#

image
A colour parameter

image
Checking the value of a parameter and throwing an exception

type Car(colour: string, wheelCount: int) =
    do
        if wheelCount < 3 then 
            failwith "We'll assume that cars must have three wheels at least"
        if wheelCount > 99 then 
            failwith "That's ridiculous"
 
    // secondary default constructor
    new() = Car("red", 4)
 
    // x is the self reference.. like this.  could be anything
    member x.Move() = printfn "The %s car is moving" colour
 
let car = Car()
 
car.Move()
 
let greenCar = Car("Green",2)
greenCar.Move()

 

 

image

// standard .NET Enum type
type CarType =
    | Tricar = 0
    | StandardFourWheeler = 1
    | HeavyLoadCarrier = 2
    | ReallyLargeTruck = 3
    | CrazyHugeMythical = 4
    | WeirdContraption = 5
 
type Car(colour: string, wheelCount: int) =
    do
        if wheelCount < 3 then 
            failwith "We'll assume that cars must have three wheels at least"
        if wheelCount > 99 then 
            failwith "That's ridiculous"
 
    let carType = 
        match wheelCount with
            | 3 -> CarType.Tricar
            | 4 -> CarType.StandardFourWheeler
            | 6 -> CarType.HeavyLoadCarrier
            // An odd number of wheels
            | x when x % 2 = 1 -> CarType.WeirdContraption
            | _ -> CarType.CrazyHugeMythical
 
    // Secondary default constructor
    new() = Car("red", 4)
 
    // x is the self reference.. like this.  could be anything.. 
    // %A is Any..makes it ToString()
    member x.Move() = printfn "The %s car (%A) is moving" colour carType
 
let car = Car()
car.Move()
 
let greenCar = Car("Green",5)
greenCar.Move()
| | # 
( F# | Unit Testing | Xunit )

New project. F# Library
Get rid of script file

image
Add in xunit

Xunit

http://blogs.jetbrains.com/dotnet/2013/01/resharper-plugins-for-unit-testing-mspec-xunitnet-and-silverlight/

http://xunitcontrib.codeplex.com/releases – need this plugin for R#

image
Ctrl U L – Run all Unit Tests in solution

| | # 
# Wednesday, 17 July 2013
( F# )

image

asdf

image

image

image
Very concise

// referenced System.Windows.Forms and System.Windows.Drawing
 
// like using in C#
open System.Windows.Forms
 
// a new type... a record.. with fields
type Person = { Name: string; Age: int}
 
// making a Person array
let testData =
    [|
        {Name = "Harry"; Age=37};
        {Name="July"; Age=41}
    |]
 
// new optional as IDisposable is implemented, so convention is don't need to use new
 
// even though no parameters in constructor, F# will new up the Form, then named parameter sytax, use properties accessors to set the value into a property called Text
let form = new Form(Text = "F# Windows Form")
 
let dataGrid = new DataGridView(Dock=DockStyle.Fill, DataSource=testData)
form.Controls.Add(dataGrid)
 
Application.Run(form)

WPF

image

open System
open System.Windows
open System.Windows.Controls
 
let loadWindow() =
    let resourceLocator = new Uri("/HelloWorldWPF;component/MainWindow.xaml", UriKind.Relative)
    // casting to Window
    let window = Application.LoadComponent(resourceLocator) :?> Window
    (window.FindName("clickButton") :?> Button).Click.Add(
        // adding lambda expression... don't care about parameters so using _
        // bad to ignore return values of functions... MessageBox has a return value.. so can pipe return value into a helper function called ignore
        fun _ -> MessageBox.Show("Hello World!") |> ignore)
    window
 
// like the main program
// attribute - make sure main code is running in correct threading model
[<STAThread>]
(new Application()).Run(loadWindow()) |> ignore

REPL – FSI The Interactive Environment

Read Eval Print Loop

Alt + #  - Runs current line in interactive window

can do multiple lines

let a = 100;;   // notice line termination just in the interactive environment

| | # 
# Tuesday, 09 July 2013
( F# )

Am exploring F# because a functional mindset helps in

  • Referential transparency – fewer defect, easier to debug with things depending less on mutability

image

Ctrl+Enter runs code

| | #