日期:2014-05-17  浏览次数:21127 次

C#函数式编程入门之快速排序
本帖最后由 caozhy 于 2013-09-19 19:12:43 编辑
之前有人提出C#实现Currying太难看,也有人提出了F#。于是我又用F#写了下之前的那几个例子程序
第一个
    let add x y = x + y
    let mutable i = add 3 4
    printfn "%d" i


第二个
    let addTen x = add 10 x
    let mutable i = add 3 4
    let mutable j = addTen i
    printfn "%d" j


第三个
    let eval x y z = y x z
    let add x y = x + y
    let mutable i = eval 3 add 5
    printfn "%d" i


第四个
    let eval x y z = y x z
    let sub x y = x - y
    let mutable i = eval 8 sub 1
    printfn "%d" i


最后一个
    let outputArray = Array.iter (fun x -> printfn "%d" x)
    outputArray [| 1; 2; 3; 4; 5 |] 


和C#的版本一比较,真是太优雅了!

好了,开始正题:

之前我在论坛贴了一个神奇的程序,用Lisp进行的快速排序
quicksort [] = []
quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater)
    where
        lesser = filter (< p) xs
        greater = filter (>= p) xs


有人表示看天书一样,为了解释原理,我用C#改写了一个,代码稍微猥琐了点,但是还是很简洁的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {        
        static void Main(string[] args)
        {
            Func<Func<int, int, bool>, Func<int[], int[]>> filter =
                x => new Func<int[], int[]>(y => y.Skip(1).Where(z => x(y[0], z)).ToArray());
            Func<int[], int[]> qsort = x => x;
            Func<int[], int[]> lesser = dt => filter((x, y) => y < x)(dt);
            Func<int[], int[]> greater = dt => filter((x, y) => y >= x)(dt);
       &nbs