F#初试(2)
2010-11-29 18:03 破狼 阅读(456) 评论(0) 编辑 收藏 举报这里只是几个f#简单的算法应用,请各位别怕砖。
代码
1 // Learn more about F# at http://fsharp.net
2
3 #light
4 open System
5
6
7 //简单的网页抓取
8 open System.Text
9 open System.IO
10 open System.Net
11 let http (url:string)=
12 let request=System.Net.WebRequest.Create(url)
13 let response=request.GetResponse()
14 let stream=response.GetResponseStream()
15 let reader=new System.IO.StreamReader(stream)
16 let html =reader.ReadToEnd();
17 html
18 printfn "%s" (http "http://www.google.com")
19
20 //汉罗塔问题:
21 let rec HanLiTa n a b c =
22 match n with
23 | 1 -> printfn " Move %s to %s ;" a c
24 | num -> HanLiTa (num-1) a c b ;HanLiTa 1 a b c ; HanLiTa (num-1) b a c ;
25
26 let n=4
27 printfn "HanLiTa start (%d):" n
28 HanLiTa n "A" "B" "C"
29
30 //Fibonacci基数
31
32 let rec Fib n =
33 match n with
34 |2 |1 -> 1
35 |i when i >1 -> Fib (i-1) + Fib (i-2)
36 |x when x<= 0 -> failwith " you should input a Interger;"
37
38 let fibn=5
39 printfn "Fibonacci %d : %d" fibn (Fib fibn)
40
41
42 //杨辉三角
43 let rec combi n r =
44 let p=ref 1;
45 [1 .. r] |> List.iter(fun g -> p:=!p*(n-g+1)/g );
46 !p
47
48 let CombiPrint N=
49 [0 .. N] |>
50 List.iter(fun g -> ([0 .. g] |>
51 List.iter(fun h->
52 if h=0 then
53 [0..(N-g)] |>
54 List.iter(fun s->printf " ") ;
55 printf "%5d" (combi g h));
56 printf "\r\n"));
57
58 printfn "\r\n杨辉三角:"
59 CombiPrint 10
60
61
62 Console.Read() |>ignore
2
3 #light
4 open System
5
6
7 //简单的网页抓取
8 open System.Text
9 open System.IO
10 open System.Net
11 let http (url:string)=
12 let request=System.Net.WebRequest.Create(url)
13 let response=request.GetResponse()
14 let stream=response.GetResponseStream()
15 let reader=new System.IO.StreamReader(stream)
16 let html =reader.ReadToEnd();
17 html
18 printfn "%s" (http "http://www.google.com")
19
20 //汉罗塔问题:
21 let rec HanLiTa n a b c =
22 match n with
23 | 1 -> printfn " Move %s to %s ;" a c
24 | num -> HanLiTa (num-1) a c b ;HanLiTa 1 a b c ; HanLiTa (num-1) b a c ;
25
26 let n=4
27 printfn "HanLiTa start (%d):" n
28 HanLiTa n "A" "B" "C"
29
30 //Fibonacci基数
31
32 let rec Fib n =
33 match n with
34 |2 |1 -> 1
35 |i when i >1 -> Fib (i-1) + Fib (i-2)
36 |x when x<= 0 -> failwith " you should input a Interger;"
37
38 let fibn=5
39 printfn "Fibonacci %d : %d" fibn (Fib fibn)
40
41
42 //杨辉三角
43 let rec combi n r =
44 let p=ref 1;
45 [1 .. r] |> List.iter(fun g -> p:=!p*(n-g+1)/g );
46 !p
47
48 let CombiPrint N=
49 [0 .. N] |>
50 List.iter(fun g -> ([0 .. g] |>
51 List.iter(fun h->
52 if h=0 then
53 [0..(N-g)] |>
54 List.iter(fun s->printf " ") ;
55 printf "%5d" (combi g h));
56 printf "\r\n"));
57
58 printfn "\r\n杨辉三角:"
59 CombiPrint 10
60
61
62 Console.Read() |>ignore
作者:破 狼
出处:http://www.cnblogs.com/whitewolf/
本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。该文章也同时发布在我的独立博客中-个人独立博客、博客园--破狼和51CTO--破狼。