50 lines
1.5 KiB
Plaintext
50 lines
1.5 KiB
Plaintext
% Sort three variables.
|
|
% The variables must all be of the same type, and the type
|
|
% must implement the less-than comparator.
|
|
sort_three = proc [T: type] (x,y,z: T) returns (T,T,T)
|
|
where T has lt: proctype (T,T) returns (bool)
|
|
if y<x then x,y := y,x end
|
|
if z<y then y,z := z,y end
|
|
if y<x then x,y := y,z end
|
|
return(x,y,z)
|
|
end sort_three
|
|
|
|
% Test it out on three values, when also given a type and a
|
|
% formatter.
|
|
example = proc [T: type] (x,y,z: T, fmt: proctype (T) returns (string))
|
|
where T has lt: proctype (T,T) returns (bool)
|
|
po: stream := stream$primary_output()
|
|
|
|
% Print the variables
|
|
stream$putl(po, "x=" || fmt(x)
|
|
|| " y=" || fmt(y)
|
|
|| " z=" || fmt(z))
|
|
|
|
% Sort them
|
|
x,y,z := sort_three[T](x,y,z)
|
|
|
|
% Print them again
|
|
stream$putl(po, "x=" || fmt(x)
|
|
|| " y=" || fmt(y)
|
|
|| " z=" || fmt(z)
|
|
|| "\n")
|
|
end example
|
|
|
|
% And then we also need formatters, since those are not standardized
|
|
% such as '<' is.
|
|
fmt_real = proc (n: real) returns (string)
|
|
return(f_form(n,2,2))
|
|
end fmt_real
|
|
|
|
fmt_str = proc (s: string) returns (string)
|
|
return( "'" || s || "'" )
|
|
end fmt_str
|
|
|
|
% Test it out on values of each type
|
|
start_up = proc ()
|
|
example[int] (77444, -12, 0, int$unparse)
|
|
example[real] (11.3, -9.7, 11.17, fmt_real)
|
|
example[string] ("lions, tigers and", "bears, oh my!",
|
|
"(from the \"Wizard of Oz\")", fmt_str)
|
|
end start_up
|