Task

Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.

Note: The order of the middle digits should be preserved.

Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:

123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0

Show your output on this page.




 
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
#include
"share/HATS/atspre_staload_libats_ML.hats"
//
(* ****** ****** *)
//
extern
fun
int2digits(x: int): list0(int)
//
(* ****** ****** *)
 
implement
int2digits(x) =
loop(x, list0_nil) where
{
//
fun
loop
(
 x: int, res: list0(int)
) : list0(int) =
  if x > 0 then loop(x/10, list0_cons(x%10, res)) else res
//
} (* end of [int2digits] *)
 
(* ****** ****** *)
 
extern
fun
Middle_three_digits(x: int): void
 
(* ****** ****** *)
 
implement
Middle_three_digits
  (x0) = let
//
val x1 =
(
if x0 >= 0 then x0 else ~x0
) : int
//
fun
skip
(
ds: list0(int), k: int
) : list0(int) =
  if k > 0 then skip(ds.tail(), k-1) else ds
//
val ds =
  int2digits(x1)
//
val n0 = length(ds)
//
in
//
if
(n0 <= 2)
then
(
println! ("Middle-three-digits(", x0, "): Too small!")
)
else
(
if
(n0 % 2 = 0)
then
(
println!
(
"Middle-three-digits(", x0, "): Even number of digits!"
)
)
else let
  val ds =
    skip(ds, (n0-3)/2)
  val-list0_cons(d1, ds) = ds
  val-list0_cons(d2, ds) = ds
  val-list0_cons(d3, ds) = ds
in
  println! ("Middle-three-digits(", x0, "): ", d1, d2, d3) 
end // end of [else]
)
//
end // end of [Middle_three_digits]
 
(* ****** ****** *)
 
implement
main0() =
{
//
val
thePassing =
g0ofg1
(
$list{int}
(
  123
, 12345
, 1234567
, 987654321
, 10001, ~10001
, ~123, ~100, 100, ~12345
)
)
val
theFailing =
g0ofg1($list{int}(1, 2, ~1, ~10, 2002, ~2002, 0))
//
val () = thePassing.foreach()(lam x => Middle_three_digits(x))
val () = theFailing.foreach()(lam x => Middle_three_digits(x))
//
} (* end of [main0] *)
 
(* ****** ****** *)
 