F#真优美...
QuickSort
let rec quickSort = function
| [] -> []
| pivot::rest ->
let left, right = List.partition (fun x -> x < pivot) rest
quickSort left @ [pivot] @ quickSort right
测试代码
open System;
let mutable random = new Random();
[1..100]
|> List.map (fun x -> random.Next(1000))
|> quickSort
|> printfn "%A"
Huffman Tree
//Data Structure Definition
type tree =
| Node of string * float * tree * tree
| Null
let ArrayToTrees arr =
[ for x in arr ->
let (c, f) = x
Node(c, f, Null, Null)]
//get data
open System;
open System.IO;
let lines = File.ReadAllLines(@"C:\Users\v-grw\Desktop\Data.txt")
let mutable trees =
lines
|> Array.map (fun x ->
let strParts = x.Split(',')
(strParts.[0], Double.Parse(strParts.[1])))
|> Seq.ofArray
|> ArrayToTrees
//Huffman tree
for i in [1..trees.Length - 1] do
trees <- trees |> List.sortBy (fun x ->
match x with
| Node(s, f, l, r) -> f
| Null -> Double.MaxValue)
match trees.[0] with
| Node(s1, f1, l1, r1) ->
match trees.[1] with
| Node(s2, f2, l2, r2) ->
let newTree = Node(s1 + s2, f1 + f2, trees.[0], trees.[1]);
trees <-
[2..trees.Length - 1]
|> List.map (fun i -> trees.[i])
|> List.append [newTree]
printfn "%A" trees.[0]
不论是对树的定义还是建树的过程都很美...