/* Middle three digits (Rosetta code) in Picat. http://rosettacode.org/wiki/Middle_three_digits """ The task is to: "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. """ This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ % import util. % import cp. main => go. 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), nl. test(List,F) => printf("\nTesting %w:\n", F), foreach(N in List) catch(Middle=apply(get_middle,N,F), E, println([n=N,exception=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). % another approach get_middle_f2(Str) = Str[Mid-1..Mid+1] => Mid = 1 + Str.length div 2.