Tuesday, February 19, 2013

Type dispatch with F# pattern match

(In learning from "Programming F# 3.0, 2nd Edition")

In F#, type dispatch is made with pattern match.
> let whatTypeNumberIs (n:obj) =
-   match n with
-   | :? int16 | :? int32 | :? int64 as i -> "This is int."
-   | :? uint16 | :? uint32 | :? uint64 as ui -> "This is uint."
-   | :? double as d -> "This is double."
-   | :? single as s -> "This is single."
-   | _ -> "This is not a number.";;

val whatTypeNumberIs : n:obj -> string

> whatTypeNumberIs 2;;
val it : string = "This is int."
> whatTypeNumberIs 2.0;;
val it : string = "This is double."

No comments:

Post a Comment