代码改变世界

F# (Part one)

2011-01-21 08:17 横刀天笑 阅读(...) 评论(...) 编辑 收藏
   1: let x = 5
   2:  
   3: val x : int = 5
   4:  
   5: open System.Net
   6: open System.IO
   7:  
   8: //method
   9: let http (url:string) =
  10:  let req = WebRequest.Create(url)
  11:  let resp = req.GetResponse()
  12:  let stream = resp.GetResponseStream()
  13:  let reader = new StreamReader(stream)
  14:  reader.ReadToEnd()
  15:  
  16: //method type
  17: val http : string -> string
  18:  
  19: let html = http "http://www.google.com"
  20:  
  21: val html : string = "<html document>"
  22:  
  23: // |> operator
  24: let html1 = "http://www.google.com" |> http
  25:  
  26: //string list
  27: let sites = ["http://www.google.com";"http://www.baidu.com";"http://www.bing.com"]
  28:  
  29: val sites : string list = ["http://www.google.com";"http://www.baidu.com";"http://www.bing.com"]
  30:  
  31: //map method
  32: let contents = sites |> List.map http 
  33:  
  34: //list
  35: ["";"";""]
  36: //array
  37: [|"";"";""|]
  38: //option
  39: Some(4,5,6)
  40: None
  41: //seq
  42: seq{1..100}
  43: val it : seq<int> = seq[1;2;3;4;..]
  44: seq{1..5..100}
  45: seq{for i in 1 to 100 -> i*i}
  46: //tuple
  47: ("keyword1",5)
  48:  
  49: //rec function
  50: let rec length l =
  51:  match l with
  52:  | [] -> 0
  53:  | h :: t -> 1 + length t
  54:  
  55: //pattern match
  56:  match aList with
  57:  |[] -> 0
  58:  |h :: t -> 1 + length t
  59:  
  60:  match aOption with
  61:  | Some(a,b) -> printfn "%s %s" a b
  62:  | None -> printfn "nothing"
  63:  
  64: //function value
  65: List.map (fun x -> x*x - 5) [5;6;7;8]