Pages

Sunday, September 25, 2011

Sample in Detail - SQL Type Provider and SQL query

SQL TypeProvider samples are recently removed from the sample package. Those samples are trying to map SQL query to F# query. SQL query has been there for decades and large number of persons are using it every day.



SQL Statement (not case-sensitive)
F# query (case-sensitive)
C# query (case-sensitive)
1
select * from Student
where exists
(select * from CourseSelection
where CourseSelection.StudentID = 1)
let q =
    query {
        for i in db.Students do
        where (query { for c in db.CourseSelection do
                       exists (c.StudentID = 1) })
        select i }
var q = from n in db.Students
                    where (from m in db.CourseSelections
                           where m.StudentID == 1
                           select m).Any()
                    select n;
1a
select Student.Age, COUNT(*)
from Student
group by Student.Age
having student.Age > 1
let q = query {
        for n in db.Student do
        groupBy n.Age into g
        where (g.Key.HasValue && g.Key.Value > 1)
        select (g.Key, g.Count())
}

var q = from n in db.Students
                    where n.Age > 1
                    group n by n.Age into g
                    select new { g.Key, Count = g.Count() };
1b
select Student.Age, COUNT(*)
from Student
group by Student.Age
having COUNT(*) > 1
let q = query {
        for n in db.Student do
        groupBy n.Age into g
        where (g.Count()>1)
        select (g.Key, g.Count())
}

var q = from n in db.Students
                    group n by n.Age into g
                    where g.Count() > 1
                    select new { g.Key, Count = g.Count() };
1c
select Student.Age, COUNT(*), SUM(Student.Age) as total
from Student
group by Student.Age
let q = query {
        for n in db.Student do
        groupBy n.Age into g       
        let t = query { for n in g do sumByNullable n.Age }
        select (g.Key, g.Count(), t)
}
var q = from n in db.Students
                    group n by n.Age into g
                    where g.Count() > 1
                    select new { Age=g.Key, Sum=g.Sum(s=>s.Age), Count = g.Count() };
1d
select Student.Age, COUNT(*) as MyCount
from Student
group by Student.Age
having COUNT(*) > 1
order by COUNT(*) desc
let q = query {
        for n in db.Student do
        groupBy n.Age into g
        where (g.Count() > 1)
        sortByDescending ( g.Count() )
        select (g.Key, g.Count())       
}
var q = from n in db.Students
                    group n by n.Age into g
                    where g.Count()>1
                    orderby g.Count() descending
                    select new { Age = g.Key, Count=g.Count() };
2
select top 2 * from Student
where student.Name like '_a'
open System.Data.Linq.SqlClient;

let q = query {
    for n in db.Student do
    where (SqlMethods.Like( n.Name, "_a") )
    select n
    take 2  
    }
var q = (from n in db.Students                   
                    where SqlMethods.Like(n.Name, "_a")
                    select n).Take(2);
3
select * from Student
where student.Name like '[abc]%'
open System.Data.Linq.SqlClient;

let q = query {
    for n in db.Student do
    where (SqlMethods.Like( n.Name, "[abc]%") )
    select n   
    }
var q = from n in db.Students                   
                    where SqlMethods.Like(n.Name, "[abc]%")
                    select n;
4
select * from Student
where student.Name like '[^abc]%'
open System.Data.Linq.SqlClient;

let q = query {
    for n in db.Student do
    where (SqlMethods.Like( n.Name, "[^abc]%") )
    select n   
    }
var q = from n in db.Students                   
                    where SqlMethods.Like(n.Name, "[^abc]%")
                    select n;
5
select StudentID as ID from Student
where student.Name like '[^abc]%'
open System.Data.Linq.SqlClient;

let q = query {
    for n in db.Student do
    where (SqlMethods.Like( n.Name, "[^abc]%") )
    select n.StudentID   
    }
var q = from n in db.Students                   
                    where SqlMethods.Like(n.Name, "[^abc]%")
                    select n.StudentID;
6
select * from
Student left join CourseSelection
on Student.StudentID = CourseSelection.StudentID
let q2 = query {
        for n in db.Student do
        join (for e in db.StudentID -> n.StudentID = e.CourseID.Value)
        select n
    }

let q = query {
    for n in q2.DefaultIfEmpty() do
    select n   
    }
var q = from n in db.CourseSelections
                    join m in db.Students
                    on n.StudentID equals m.StudentID into g
                    from x in g
                    select x;
7
select * from
Student right join CourseSelection
on Student.StudentID = CourseSelection.StudentID
No match, you can reverse two tables.
No match, you can reverse two tables.
8
Select * from student
let q = query {
        for n in db.Student do
        select n
    }
var q = from n in db.Students
                    select n;
9
select count(*) from student
let q = query {
        for n in db.Student do       
        count
    }
var q = (from n in db.Students
                     select n).Count();
10
select COUNT(*) from
Student join CourseSelection
on Student.StudentID = CourseSelection.StudentID
let q = query {
        for n in db.Student do
        join (for e in db.CourseSelection -> n.StudentID = e.StudentID)
        count       
    }
var q = (from n in db.CourseSelections
                    join m in db.Students
                    on n.StudentID equals m.StudentID into g
                    from x in g
                    select x).Count();
11
select distinct StudentID from CourseSelection
let q = query {
        for n in db.Student do
        join (for e in db.CourseSelection -> n.StudentID = e.StudentID)
        distinct       
    }
var q = (from n in db.CourseSelections
                     select n).Distinct();
12
select distinct count(StudentID) from CourseSelection
let q = query {
        for n in db.Student do
        join (for e in db.CourseSelection -> n.StudentID = e.StudentID)
        distinct
        count      
    }
var q = (from n in db.CourseSelections
                     select n).Distinct().Count();
13
select * from Student
where Student.Name like '%A%'
(not case-sensitive)
let q = query {
        for n in db.Student do
        where (n.Name.Contains("a"))
        select n
    }
(not case-sensitive)
var q = from n in db.Students                   
                    where SqlMethods.Like(n.Name, "%A%")
                    select n;
14

select
* from Student
where Student.Name in ('A', 'B', 'C')

(not case-sensitive)
Open System.Linq  //please do not forget to add this line

let names = [|"a";"b";"c"|]
let q = query {
    for n in db.Student do
    if names.Contains (n.Name) then select n }
 (not case-sensitive)
var list = new List<string>(new string[] { "a", "b", "c" });
            var q = from n in db.Students
                     where list.Contains(n.Name)
                     select n;
15
select * from Student
where Student.Age between 2 and 5
let q = query {
        for n in db.Student do
        where (n.Age.Value >=1 && n.Age.Value <5)
        select n
    }
var q = from n in db.Students
                     where n.Age>=1 && n.Age<5
                     select n;
16
select * from Student
where Student.Age =1 OR Student.Age = 2
let q = query {
        for n in db.Student do
        where (n.Age.Value =1 || n.Age.Value =2)
        select n
    }
var q = from n in db.Students
                     where n.Age==1 || n.Age==2
                     select n;
17
select * from Student
where Student.Age =1 OR Student.Age = 2
order by Student.Name desc
let db = T.GetDataContext();
let q = query {
        for n in db.Student do
        where (n.Age.Value =1 || n.Age.Value =2)
        sortByNullableDescending n.Age
        select n
    }
var q = from n in db.Students
                    where n.Age == 1 || n.Age == 2
                    orderby n.Age descending
                    select n;
18
select top 2 student.Name from Student
where Student.Age =1 OR Student.Age = 2
order by Student.Name desc

let q = query {
        for n in db.Student do
        where ((n.Age.HasValue && n.Age.Value =21) || (n.Age.HasValue && n.Age.Value=22))
        select n.Name
        take 2
    }
var q = (from n in db.Students
                    where n.Age == 1 || n.Age == 2
                    orderby n.Name descending
                    select n).Take(2);
19
select * from Student
union
select * from lastStudent
let q = query {
        for n in db.Student do
        select (n.Name, n.Age)
    }

let q2 = query {
        for n in db.LastStudent do
        select (n.Name, n.Age)
        }

let q3 = q.Union (q2)
var q = (from n in db.Students
                     select n).Union(
                    (from n in db.LastStudents
                     select n));
20
select Student.Age, COUNT(*) from Student
group by Student.Age
Open System.Linq  //please do not forget to add this line

let q = query {
        for n in db.Student do
        groupBy n.Age into g
        select (g.Key, g.Count())
}

OR

let q = query {
        for n in db.Student do
        groupValBy n.Age n.Age into g
        select (g.Key, g.Count())
    }
var q = from n in db.Students
                    group n by n.Age into g
                    select new { Age=g.Key, Count=g.Count() }
21
select student.StudentID,
      case Student.Age
            when 1 then Student.Age * 100
            else student.Age
      end,
      student.Age
from Student
let q = query {
        for n in db.Student do
        select (if n.Age.HasValue && n.Age.Value=1  then (n.StudentID, System.Nullable(n.Age.Value*100), n.Age) else (n.StudentID, n.Age, n.Age))
    }
var q = from n in db.Students                   
                    select new { n.StudentID,  Age= n.Age==1 ? n.Age*100 : n.Age};
22
select * from Student
INTERSECT
select * from LastStudent
let q = query {
        for n in db.Student do
        select (n.Name, n.Age)
    }

let q2 = query {
        for n in db.LastStudent do
        select (n.Name, n.Age)
        }

let q3 = q. Intersect (q2)
var q = (from n in db.Students
                     select n).Intersect(
                    (from n in db.LastStudents
                     select n));
23
select * from Student, Course
let q = query {
        for n in db.Student do
        for m in db.Course do
        select (n, m)
}
(need more work to flatten the structure and grab out all fields)
var q = from n in db.Students
                    from m in db.Courses
                    select new { n, m };


Saturday, September 24, 2011

Const value and F# Type Provider parameter

I guess i forget to put in a sample to show how to declare a constant in F#.

Now I found a way to use this feature with TypeProviders. The type provider is the newly introduced feature in  F#, but it has a major drawback: cannot have variable in the type declaration. When I wrote Regex Type Provider, I know why should be like this way and it is not easy to fix it. In the meanwhile, this bothers me a lot. Today at least I find a way to give a little bit more flexibility by using a const.


[ < Literal > ]
let conStr = "< my con string> "

type T = Microsoft.FSharp.Data.TypeProviders.SqlDataConnection ( constr )
let db = T.GetDataContext()

This enable me to use conditional compilation to target different database. At least a little more freedom than before.

Thursday, September 22, 2011

Sample in detail - Use F# measure feature

In the sample package, I wrote a small sample to explore how to use measure unit in a bank system. Why I would like to present this sample? Because I want to show not only how to use measure unit on a single value but also how to use measure unit for a complex class. You can even treat this like a class template which takes measure unit as type.


[]type JPY
[]type CNY
type BankAccount<[]'u>() =
    let mutable balance : float<'u> = 0.0<_>
    member acct.HasLotsOfMoney = balance > (LanguagePrimitives.FloatWithMeasure 10000.0) //10000 units
    member acct.Deposit(amt) = balance <- balance + amt
    member acct.Withdraw(amt) = balance <- balance - amt

let MeasureSample5() =
    let a = BankAccount()
    a.Deposit(10.)

    let b = BankAccount()
    b.Deposit(10.)

    printfn "show how to deposit right currency to right account"

If you change the deposit incorrect currency into the account, you will get a compile time error. The tricky part is to use LanguagePrimitives.FloatWithMeasure in the sample. please make sure all constant in the type definition is always use  LanguagePrimitives.FloatWithMeasure.

Monday, September 19, 2011

F# with less bug and C# structure mapping

When I program with F#, I find less bugs are yielded. I can confirm this astonishing result with some other individuals or companies. I want to know find out why and here is something I've got on the top of my mind:

1. mutable variable is not allowed. Less mutable variable means less state and lower possibility to generate bug.
2. concise code. this is pretty straightforward. The probability is proportional  to the length of code.
3. mind set change. I do not intend to speak for other person. For me, when I changed my mind set from C++ machine-like thinking to more math-like thinking. I find it is natural to solve a program with less glitch. When I not forced to think like a computer, I feel a big relief and my brain becomes more efficient. 

Let me mapping the basic C# flow control structure to F#.

FOR loop

for (int i=0; i<100; i++) ...

can be written as

[0..99] |> Seq.map (fun i -> ... )

this approach can be interpreted as loop on the list [0..99]. Another way to interpreted this is the result is a transform of element in [0..99]. This transform is performed by a function applied to the element in [0..99].

Please note: this approach create a list in the memory, if this is too much memory cost, then you can use seq instead of list.

FOR Loop with IF inside

for (int i=0; i<100; i++)
    if (i % 2 == 0) ....

notice the above sample does not have ELSE.

[0..99] |> Seq.filter (fun i->i %2 = 0) |> Seq.map (fun i -> ....)

the list [0..99] is filtered to make sure only the valid input is going to be processed.

we usually make a lot of operations in a FOR loop to improve performance. With parallel in mind, maybe we want to change this behavior. For example, we perform functionA on even number and functionB on odd number. Instead of doing:

//C# pseudo code
for i =0 to 99 do
    if i %2 = 0 then functionA()
    else functionB()

We can do
[0..99] |> Seq.filter (fun n -> n%2=0) |> Seq.map (fun i -> functionA())
[0..99] |> Seq.filter (fun n -> n%2<> 0) |> Seq.map (fun i -> functionB())

And put these two statements onto two processors. Which one is faster, it might depends on the implementation. But I prefer the F# version. Immutable data and parallel are friend. Most of our existing algorithm is based on single process. That's why I like F# more.

WHILE loop

During the flight from Seattle to Louisvelle, I was thinking about the WHILE loop. FOR loop has more well defined boundary, but WHILE loop is behave otherwise. Is there a way to transfer WHILE loop to F#? I prefer to use Seq's infinite seq feature. Seq.initInfinite gives a infinite seq as the input into your function. Its your function's job to generate a value which can be track by Seq.takwhile function, so the loop won't go into infinite loop. For me I pay more attention to how to terminate the loop from the function and usually got a math formula written down. This formula gives me more confidence not going to an infinite loop.

Last Chapter
Today is the last night at the nice town Louisville, KY. I love this place better than Seattle. Enough, back to work! Let me finish this post with a sort algorithm implementation.

If we use parallel to solve a sorting problem, what could be the solution? An element's index in a sorted list is the number of element smaller (or bigger) than this element. If we have multiple processor, can we just process compute the index from existing array. Because the existing array is immutable, so all the process can be paralleled. Let us assume the processor number is large enough, we can readily get O(n).

I start to think about my breakfast. do not really want these algorithms to interrupt.. :-)

Wednesday, September 14, 2011

F# sample package is published

more than 200 samples. Enjoy!

http://fsharp3sample.codeplex.com/

The type provider is a new feature. More sample or blog will be published to help people understand this new feature.

I will publish some posts about how these new samples in the near future.