Re: [ats-lang-users] template functions vs polymorpdic functions
Unleashing the potentials of types and templates
Status: Beta
Brought to you by:
ats-hwxi
From: Hongwei Xi <hw...@cs...> - 2010-04-05 11:03:07
|
On Mon, 5 Apr 2010, Rouan van Dalen wrote: >>Hi Hongwei >> >>I was wondering why ATS has template functions AND polymorphic functions? >> >>Where would I rather use a template than a polymorphic function? Say you have the following function: fun f {a:type} (x: a): a = x 'f' is polymorphic. However, 'f' can only be applied to a boxed value. E.g., f(0.0) results in a type error as 'double' is not a boxed type. BTW, all datatypes are boxed. Suppose we implement f as follows: fun f {a:t@ype} (x: a): a = x Unfortuately, this function cannot be compiled as the size of 'a' is unknown at compile-time. In ATS, 'f' can be implemented as follows: fun{a:t@ype} f (x: a): a = x This is a function template. Just like in C++, a template is not compiled until it is applied. If you call f(1), then *essentially*, the following function is generated fun f_int (x: int): x = x and the call becomes f_int(1). If you call f(1.0), then the following function is generated: fun f_double (x: int): x = x and the call becomes f_double(1.0). In pratice, I find templates to be extremely useful, especially, when implementing library code. Hope this helps, --Hongwei Computer Science Department Boston University 111 Cummington Street Boston, MA 02215 Email: hw...@cs... Url: http://www.cs.bu.edu/~hwxi Tel: +1 617 358 2511 (office) Fax: +1 617 353 6457 (department) |