// The sports team program in F#, illustrating classes open System let rand = Random();; // random number generator (from .Net API) type team = val total:int val mutable wins:int val mutable losses:int new(t) = {total=t; wins=0; losses=0;} // this is a record, not piece of code member this.win = this.wins <- this.wins+1 member this.lose = this.losses <- this.losses+1 abstract member wp: unit -> float default this.wp () = let games = float (this.wins+this.losses) in if (games=0.0) then 0.0 else (float this.wins)/games member this.play (t2:team) = // the ()'s are necessary let r = rand.NextDouble() in if r<0.5 then this.win; t2.lose; printfn "I win, you suck"; else this.lose; t2.win; printfn("You win, but you still suck");; // team let jets = team(16);; let giants = team(16);; jets.win;; jets.lose;; Console.WriteLine(string (jets.wp));; jets.play(giants);; let winning = function // note pattern matching and type hint | ({wins=w; losses=l}:team) -> w>l;; Console.WriteLine(string (winning jets));; /////////////// inheritance: teams that can tie type tieteam = inherit team val mutable ties:int member this.tie = this.ties <- this.ties+1 new(t) = { inherit team(t); ties=0 } override this.wp () = let games = float(this.wins+this.losses+this.ties) in if (games=0.0) then 0.0 else (float(this.wins)+(float(this.ties)/2.0))/games;; let t1 = tieteam(16);; t1.tie;; t1.win;; t1.lose;; t1.lose;; Console.WriteLine(string(t1.wp()));;