N'th: Difference between revisions

Content added Content deleted
No edit summary
(→‎{{header|Picat}}: Split into subsections)
Line 2,933: Line 2,933:


=={{header|Picat}}==
=={{header|Picat}}==
nth/3 is a built-in predicate in Picat, so let's call the function nth2/1 and onward.
<code>nth/3</code> is a built-in predicate in Picat, so let's call the functions <code>nth2/1</code> and onward.
===Prolog style===

* nth2/1: {{trans|Prolog}}
{{trans|Prolog}}
<lang Picat>nth2(N) = N.to_string() ++ Th =>
* nth3/1: Function based with explicit conditions in head.
* nth4/1: {{trans|Python}}

<lang Picat>go =>
Ranges = [ 0..25, 250..265, 1000..1025],
foreach(Range in Ranges) println([nth2(I) : I in Range])
end,
nl.

%
% Translation of Prolog version
%
nth2(N) = N.to_string() ++ Th =>
( tween(N) -> Th = "th"
( tween(N) -> Th = "th"
; 1 = N mod 10 -> Th = "st"
; 1 = N mod 10 -> Th = "st"
Line 2,954: Line 2,942:
; 3 = N mod 10 -> Th = "rd"
; 3 = N mod 10 -> Th = "rd"
; Th = "th" ).
; Th = "th" ).
tween(N) => Tween = N mod 100, between(11, 13, Tween).
tween(N) => Tween = N mod 100, between(11, 13, Tween).</lang>


===Function with explicit conditions===
%
<lang Picat>nth3(N) = cc(N,"th"), tween(N) => true.
% Using explicit conditions
%
nth3(N) = cc(N,"th"), tween(N) => true.
nth3(N) = cc(N,"st"), N mod 10 = 1 => true.
nth3(N) = cc(N,"st"), N mod 10 = 1 => true.
nth3(N) = cc(N,"nd"), N mod 10 = 2 => true.
nth3(N) = cc(N,"nd"), N mod 10 = 2 => true.
Line 2,965: Line 2,951:
nth3(N) = cc(N,"th") => true.
nth3(N) = cc(N,"th") => true.
% helper function
% helper function
cc(N,Th) = N.to_string() ++ Th.
cc(N,Th) = N.to_string() ++ Th.</lang>


===List of suffixes===
%
{{trans|Python}}
% Translation of the Python version
<lang Picat>nth4(N) = Nth =>
%
nth4(N) = Nth =>
Suffix = ["th","st","nd","rd","th","th","th","th","th","th"],
Suffix = ["th","st","nd","rd","th","th","th","th","th","th"],
Nth = N.to_string() ++ cond((N mod 100 <= 10; N mod 100 > 20), Suffix[1 + N mod 10], "th").</lang>
Nth = N.to_string() ++ cond((N mod 100 <= 10; N mod 100 > 20), Suffix[1 + N mod 10], "th").</lang>

===Test===
<lang Picat>go =>
Ranges = [ 0..25, 250..265, 1000..1025],
foreach(Range in Ranges) println([nth2(I) : I in Range])
end,
nl.</lang>


{{out}}
{{out}}