RosettaCodeData/Task/Sort-three-variables/BCPL/sort-three-variables.bcpl

49 lines
1.2 KiB
Plaintext

get "libhdr"
// Sort 3 variables using a comparator.
// X, Y and Z are pointers.
let sort3(comp, x, y, z) be
$( sort2(comp, x, y)
sort2(comp, x, z)
sort2(comp, y, z)
$)
and sort2(comp, x, y) be
if comp(!x, !y) > 0
$( let t = !x
!x := !y
!y := t
$)
// Integer and string comparators
let intcomp(x, y) = x - y
let strcomp(x, y) = valof
$( for i=1 to min(x%0, y%0)
unless x%i = y%i
resultis intcomp(x%i, y%i)
resultis intcomp(x%0, y%0)
$)
and min(x, y) = x < y -> x, y
// Run the function on both ints and strings
let start() be
$( printAndSort(writen, intcomp, 7444, -12, 0)
printAndSort(writes, strcomp,
"lions, tigers, and",
"bears, oh my!",
"(from the *"Wizard of OZ*")")
$)
// Print the 3 values, sort them, and print them again
and printAndSort(printfn, comp, x, y, z) be
$( print3(printfn, x, y, z) ; writes("*N")
sort3(comp, @x, @y, @z)
print3(printfn, x, y, z) ; writes("------*N")
$)
// Print 3 values given printing function
and print3(printfn, x, y, z) be
$( writes("X = ") ; printfn(x) ; wrch('*N')
writes("Y = ") ; printfn(y) ; wrch('*N')
writes("Z = ") ; printfn(z) ; wrch('*N')
$)