Pages

Tuesday, August 9, 2011

F# basic data types and printfn

do not want to look up those symbols every time:


let int = 42
let string = "This is a string"
let char = 'c'
let bool = true
let bytearray = "This is a byte string"B
let hexint = 0x34
let octalint = 0o42
let binaryinteger = 0b101010
let signedbyte = 68y
let unsignedbyte = 102uy
let smallint = 16s
let smalluint = 16us
let integer = 345l
let usignedint = 345ul
let nativeint = 765n
let unsignednativeint = 765un
let long = 12345678912345L
let unsignedlong = 12345678912345UL
let float32 = 42.8F
let float = 42.8

printfn "int = %d or %A" int int
printfn "string = %s or %A" string string  //nice we have double quote around the string when use %A
printfn "char = %c or %A" char char  //nice we have single quote around the character when use %A
printfn "bool = %b or %A" bool bool
printfn "bytearray = %A" bytearray
printfn "hex int = %x or %A" hexint hexint
printfn "HEX INT = %X or %A" hexint hexint
printfn "oct int = %o or %A" octalint octalint
printfn "bin int = %d or %A" binaryinteger binaryinteger
printfn "signed byte = %A" signedbyte
printfn "unsigned byte = %A" unsignedbyte
printfn "small int = %A" smallint
printfn "small uint = %A" smalluint
printfn "int = %i or %A" integer integer
printfn "uint = %i or %A" usignedint usignedint
printfn "native int = %A" nativeint
printfn "unsigned native int = %A" unsignednativeint
printfn "long = %d or %A" long long
printfn "unsigned long = %A" unsignedlong
printfn "float = %f or %A" float32 float32
printfn "double = %f or %A" float float

Saturday, July 16, 2011

How to get all the stored procedures in SQL Server in F#

Be very careful about the last List.map, if you change it to Seq.map, the lazy evaluation will catch you later on. Because the connection is closed when you actually leave this function, but the value is still on the server side if you use Seq.map. When you try to reference those values, you are screwed.

let getStoredProcedureParameters (connectionString, includeSystemSP) =
    use con = new SqlConnection (connectionString)      
    con.Open()

    let getSPParameters storedProcedureName =
        let cmd = con.CreateCommand()
        cmd.CommandType <- CommandType.StoredProcedure
        cmd.CommandText <- storedProcedureName

        SqlCommandBuilder.DeriveParameters(cmd);
        seq {
            for i in [0..cmd.Parameters.Count-1] do
            let p = cmd.Parameters.[i]
            yield (p.ParameterName, (p.DbType, p.IsNullable, p.Direction) )
        }

    let getAllStoredProcedureNames isIncludeSystemSP =                      
        let userSPNames =
            let query = @"SELECT * from SYS.PROCEDURES"
            use userSPCmd = con.CreateCommand()
            userSPCmd.CommandText <- query
            use reader = userSPCmd.ExecuteReader()
            [
                while reader.Read() do
                    yield reader.[0].ToString()
            ]
        if isIncludeSystemSP then
            let query = @"select name from sys.all_objects where is_ms_shipped = 1 and type = 'P' order by name"
            let cmd = con.CreateCommand()
            cmd.CommandText <- query;
            use reader = cmd.ExecuteReader()
            let result =
                [
                    while reader.Read() do
                        yield reader.[0].ToString()
                ]
            userSPNames @ result
        else
            userSPNames
   
    includeSystemSP |> getAllStoredProcedureNames |> List.map getSPParameters

Friday, July 15, 2011

Convert the C# type including nullable to F# Option

public static FSharpOption ToFSharpOption(this T obj)
        {
            if (obj.IsNullable())
            {
                var type = Nullable.GetUnderlyingType(typeof(T));
                var result = obj == null ? FSharpOption.None : FSharpOption.Some(obj);
                return result;
            }
            else
            {
                var result = obj == null ? FSharpOption.None : new FSharpOption(obj);
                return result;
            }
        }

        public static bool IsNullable(this T obj)
        {
            if (obj == null)
                return true;
            Type type = typeof(T);
            if (!type.IsValueType)
                return true; //ref type
            if (Nullable.GetUnderlyingType(type) != null)
                return true; // Nullable
            return
                false; // value-type
        }

Wednesday, May 4, 2011

Prepare for a move - algorithm

Most of the algorithm is like solving a puzzle, it is interesting, but it lacks of math. I came across an algorithm problem, which is interesting to me, at least more math involved.

Given a complete binary search tree in form of array. Write a sort function to sort the given array in O(n)time complexity and constant memory.

________100
_____50_______150
___25___75__125___200

then array is {100 50 150 25 75 125 200}

the trick is the tree is a full binary tree.

if the node is left most node: its index = (0 + parent node's index) / 2
if the node is right most node: its index = (n + parent node's index) / 2
other nodes: its index = (parent's index + grandparent's index) / 2

with this formula, it is easy to pin point the location.

Monday, May 2, 2011

Prepare for a move - threading and parallel

Finally, it is time to prepare for some move in the future. When you buried in everyday work, you must have got tunnel vision, I hope this preparation process will give me some fresh air. You might use the low performance statement every day or totally lose your mind when being ask what is "algorithm X" with O(n). :-) Let us start my journey and hopefully learn something new.

The first topic I want to touch is to use lock keyword in the C#.

if there are some variables in the class and how to use lock to update it.

if it is a int or long, use the interlock.increament if that is possible. Otherwise, the general rule is

1. declare a private or protected variable as syncroot
2. if the variable is value type, then lock the syncroot
if the variable is ref type, lock the variable itself.

Actually, if you want to get your work done, use the data structure under System.Collection.Concurrent namespace (new .net 4.0) , which is usually get rid of the need for explicit synchronization.

One catch I found is that on 32-bit system, the reading a 64-bit int is NOT atomic. You have to use Interlock.Read(). In a 64-bit system, reading 64-bit int is atomic.

Today I found the [ThreadStatic] attribute is very useful when design the multi-thread application. It has unique value for each thread!

Friday, April 29, 2011

Find the maximum difference in a sequence

Let us put another interview question solution with F# (functional way). The question is to find the x[a], x[b], where x[b] - x[a] -> maximum

we are going to find a tuple (a,b) where x[b] - x[a] -> maximum. Be careful b must be greater than a. So our first problem will be how to generate a sequence (a,b) where b>a and a between (0, L).

f(i) will generate a sequence from i to L.
f(i) -> [i..L] |> Seq.map (n-> (i,n))

[0..L]
|> Seq.map (i-> Seq.map (n->(i,n)) [i..L] ) //generate the (a,b) tuple
|> Seq.collect (n->n) //flatten the sequence
|> Seq.maxby ((a,b)->x[b]-x[a]) //find the max dif

Friday, April 15, 2011

F# and genetic algorithms

I have already three posts: fitness, chromosome, and population for the GA. Because my IEEE paper is about the chromosome encoding, so I am very interested in decouple the geno and phone mapping.

This post is to use F# implement the Genetic Algorithm (GA). This GA implementation is based on genotype and phenotype. You can add geno-to-pheno type mapping. Not like simple genetic algorithm, the chromosome is only 0 and 1, this implementation supports the integer. I believe you can support other chromosome representation easily because the beauty of F#. The chromosome representation can be generated by the initialization function. All the GA part is represented as function and you are given the liberty to pass in your function.

I also added the elitism for the evolution. (Aug 05, 2012).

Please use the link below to get the code.