Function composition: Difference between revisions

Line 430:
{{out}}
<pre>$ patscc -O2 -DATS_MEMALLOC_GCBDW function_composition.dats -lgc && ./a.out
105.000000
107.000000</pre>
 
Incidentally, it is possible to instantiate the template function and obtain a true function that does the composition. What the template does for us is give us compile-time type polymorphism. In the following, the template is instantiated as a true function for specific types:
 
<lang ats>#include "share/atspre_staload.hats"
 
fn {t1, t2, t3 : t@ype}
compose (f : t2 -<cloref1> t3,
g : t1 -<cloref1> t2) : t1 -<cloref1> t3 =
lam x => f (g (x))
 
fn
compose_char2int2double
(f : int -<cloref1> double,
g : char -<cloref1> int) :
char -<cloref1> double =
compose<char, int, double> (f, g)
 
implement
main0 () =
let
val one_hundred = 100.0
val char_zero = '0'
val f = (lam y =<cloref1> add_double_int (one_hundred, y))
val g = (lam x =<cloref1> char2i x - char2i char_zero)
val z = compose_char2int2double (f, g) ('5')
val fg = compose_char2int2double (f, g)
val w = fg ('7')
in
println! (z : double);
println! (w : double)
end</lang>
 
{{out}}
<pre>$ patscc -O2 -DATS_MEMALLOC_GCBDW function_composition_2.dats -lgc && ./a.out
105.000000
107.000000</pre>
1,448

edits