30 lines
1.0 KiB
Plaintext
30 lines
1.0 KiB
Plaintext
// 1. Create a routine to generate the hailstone sequence for a number.
|
|
type odd x::int = x mod 2;
|
|
type even x::int = ~odd x;
|
|
odd x = typep odd x;
|
|
even x = typep even x;
|
|
|
|
hailstone 1 = [1];
|
|
hailstone n::even = n:hailstone (n div 2);
|
|
hailstone n::odd = n:hailstone (3*n + 1);
|
|
|
|
// 2. Use the routine to show that the hailstone sequence for the number 27
|
|
// has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
|
|
n = 27;
|
|
hs = hailstone n;
|
|
l = # hs;
|
|
using system;
|
|
|
|
printf
|
|
("the hailstone sequence for the number %d has %d elements " +
|
|
"starting with %s and ending with %s\n")
|
|
(n, l, __str__ (hs!!(0..3)), __str__ ( hs!!((l-4)..l)));
|
|
|
|
// 3. Show the number less than 100,000 which has the longest hailstone
|
|
// sequence together with that sequences length.
|
|
printf ("the number under 100,000 with the longest sequence is %d " +
|
|
"with a sequence length of %d\n")
|
|
(foldr (\ (a,b) (c,d) -> if (b > d) then (a,b) else (c,d))
|
|
(0,0)
|
|
(map (\ x -> (x, # hailstone x)) (1..100000)));
|