Tuesday, May 31, 2011

Studying F# : inline keyword

When you define simple calculator function, you just write like below:
let add a b = a + b

There is a question. What type of these arguments? In F# interactive console, it's int, so othre numeric types is not accepted for this function.
> let add a b = a + b;;

val add : int -> int -> int

> add 2 3;;
val it : int = 5
> add 2.0 3.0;;

  add 2.0 3.0;;
  ----^^^

stdin(3,5): error FS0001: This expression was expected to have type
    int
but here has type
    float
How do we make the function acceptable other numeric types?

Generics? Generics is for classes and class members. In this sample, there is only a function, no generics are needed. Well, are there any features like "generics for functions"? The answer is inline keyword.

inline keyword enables this feature.
> let inline add a b = a + b;;

val inline add :
   ^a ->  ^b ->  ^c
    when ( ^a or  ^b) : (static member ( + ) :  ^a *  ^b ->  ^c)

> add 2 3;;
val it : int = 5
> add 2.0 3.0;;
val it : float = 5.0
> add 2 3.0;;

  add 2 3.0;;
  ------^^^

stdin(7,7): error FS0001: The type 'float' does not match the type 'int'
But arguments still must be same types.

1 comment:

Unknown said...

Thanks for this article. It's just what I was searching for. I am always interested in this subject.

PIC Scheme

Post a Comment