Wednesday, May 11, 2011

Studying F# : Interface

F# has interfaces. we can define it and use it like other object-oriented languages.

Definition


[<Interface>]
type IDrinker =
    inherit System.IComparable
    inherit System.IFormattable
    abstract Drink : unit -> unit // method definition of interface
    abstract FavoriteDrink : string // property definition of interface
Interface can inherit another interfaces multiply.

Usage


[<Class>]
type DrinkingPerson(fn, ln, a) =
    inherit System.Object()
    interface IDrinker with
        member this.CompareTo(other) =
            let other = other :?> DrinkingPerson
            let tln : string = this.LastName
            let ln = tln.CompareTo(other.LastName)
            if ln <> 0 then
                let tfn : string = this.FirstName
                let fn = tfn.CompareTo(other.FirstName)
                if fn <> 0 then
                    let ta : int = this.Age
                    ta.CompareTo(other.Age)
                else
                    fn
            else
                ln
        member this.ToString(s:string, fp:System.IFormatProvider):string =
           "Not interesting enough to implement yet"
        member this.Drink() =
            System.Console.WriteLine("Yep")
        member this.FavoriteDrink =
            "Grapefruit juice"
    override this.GetHashCode() =
        hash(fn, ln, a)
    override this.Equals(other) =
        compare this (other:?>DrinkingPerson) = 0
    member p.FirstName = fn
    member p.LastName = ln
    member p.Age = a
hash and compare are utility functions for implementing GetHashCode() and Equals(other) explicitly.

No comments:

Post a Comment