Middle three digits: Difference between revisions

(Add CLU)
Line 4,418:
-2002 : The value must contain an odd amount of digits...
0 : The value must contain at least three digits...</pre>
 
=={{header|Picat}}==
Two get_middle/1 functions:
* get_middle_f1/1: {{trans|Prolog}}
* get_middle_f2/1: Using string length and list range
 
<lang Picat>go =>
Success = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345],
Fail = [1, 2, -1, -10, 2002, -2002, 0],
All = Success ++ Fail,
 
test(All, get_middle_f1),
test(All, get_middle_f2).
 
% Test and check for exceptions
test(List,F) =>
printf("\nTesting %w:\n", F),
foreach(N in List)
catch(Middle=apply(get_middle,N,F), E, printf("%d = exception %w\n",N,E)),
if E.var() then
println([n=N,middle=Middle])
end
end,
nl.
 
% Check with the get_middle funcion F
get_middle(N,F) = apply(F,Str) =>
Str = N.abs().to_string(),
Len = length(Str),
if Len mod 2 = 0 then throw $not_odd_length(N)
elseif Len < 3 then throw $number_too_small(N)
end.
% inspired by the Prolog solution
get_middle_f1(Str) = [X,Y,Z] =>
append(Pre,[X,Y,Z],Post,Str),
length(Pre) = length(Post).
 
% Using slice
get_middle_f2(Str) = Str[Mid-1..Mid+1] =>
Mid = 1 + Str.len div 2.</lang>
 
Both tests outputs:
<pre>[n = 123,middle = 123]
[n = 12345,middle = 234]
[n = 1234567,middle = 345]
[n = 987654321,middle = 654]
[n = 10001,middle = 000]
[n = -10001,middle = 000]
[n = -123,middle = 123]
[n = -100,middle = 100]
[n = 100,middle = 100]
[n = -12345,middle = 234]
[n = 1,exception = number_too_small(1)]
[n = 2,exception = number_too_small(2)]
[n = -1,exception = number_too_small(-1)]
[n = -10,exception = not_odd_length(-10)]
[n = 2002,exception = not_odd_length(2002)]
[n = -2002,exception = not_odd_length(-2002)]
[n = 0,exception = number_too_small(0)]</pre>
 
 
=={{header|PicoLisp}}==
495

edits