Compare a list of strings: Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 26:
=={{header|11l}}==
{{trans|D}}
<
V strings = strings_s.split(‘ ’)
print(strings)
print(all(zip(strings, strings[1..]).map(a -> a[0] == a[1])))
print(all(zip(strings, strings[1..]).map(a -> a[0] < a[1])))
print()</
=={{header|360 Assembly}}==
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
<
COMPLIST CSECT
USING COMPLIST,R13 base register
Line 122:
PG DS CL80
YREGS
END COMPLIST</
{{out}}
<pre>
Line 131:
=={{header|Action!}}==
<
BYTE FUNC AreEqual(PTR ARRAY a BYTE len)
Line 196:
a4(0)="aaa"
Test(a4,1)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Compare_a_list_of_strings.png Screenshot from Atari 8-bit computer]
Line 220:
We will store the "list" of strings in a vector. The vector will hold "indefinite" strings, i.e., the strings can have different lengths.
<
(Index_Type => Positive, Element_Type => String);
use type String_Vec.Vector;</
The equality test iterates from the first to the last-but one index. For index Idx,
Line 229:
yes for any Idx, the function immediately returns False. If the answer is no for all Idx,
the function finally returns True.
<
begin
for Idx in Strings.First_Index .. Strings.Last_Index-1 loop
Line 237:
end loop;
return True;
end All_Are_The_Same;</
Similarily, the strictly ascending test checks if Strings(Idx) is greater or equal Strings(Idx+1).
<
begin
for Idx in Strings.First_Index+1 .. Strings.Last_Index loop
Line 248:
end loop;
return True;
end Strictly_Ascending;</
If the variable Strings is of the type String_Vec.vector, one can call these two functions
as usual.
<
Boolean'Image(Strictly_Ascending(Strings)));</
If Strings holds two or more strings, the result will be either of TRUE, FALSE, or FALSE, TRUE, or FALSE, FALSE, indicating all strings are the same, or they are strictly ascending, or neither.
Line 259:
=={{header|ALGOL 68}}==
<
[]STRING list2 = ("AA","AA","AA");
[]STRING list3 = ("AA","CC","BB");
Line 298:
print (("...is not in strict ascending order", new line))
FI
OD</
{{out}}
<pre>list: AA BB CC
Line 318:
=={{header|ALGOL W}}==
<
% As Algol W procedures cannot determine the bounds of an array, the bounds %
% must be specified in lo and hi %
Line 353:
end;
ordered
end ascendingOrder ;</
=={{header|AppleScript}}==
Line 361:
<
on allEqual(xs)
_and(zipWith(my _equal, xs, rest of xs))
Line 469:
end script
end if
end mReturn</
{{Out}}
Line 476:
=={{header|Arturo}}==
<
ascending?: function [lst] -> lst = sort lst
Line 490:
print ["allEqual?" allEqual? l]
print ["ascending?" ascending? l "\n"]
]</
{{out}}
Line 511:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f COMPARE_A_LIST_OF_STRINGS.AWK
BEGIN {
Line 539:
printf("\n%d\n%d\n",test1,test2)
}
</syntaxhighlight>
{{out}}
<pre>
Line 567:
If all are not equal and the list is invariant under sorting, then it is in ascending order.
<
Asc ← ¬∘AllEq∧∧≡⊢
Line 574:
•Show AllEq ⟨"AA", "ACB", "BB", "CC"⟩
•Show Asc ⟨"AA", "ACB", "BB", "CC"⟩</
<
0
0
1</
[https://mlochbaum.github.io/BQN/try.html#code=QWxsRXEg4oaQIOKNi+KJoeKNkgpBc2Mg4oaQIMKs4oiYQWxsRXHiiKfiiKfiiaHiiqIKCuKAolNob3cgQWxsRXEg4p+oIkFBIiwgIkFBIiwgIkFBIiwgIkFBIuKfqQrigKJTaG93IEFzYyDin6giQUEiLCAiQUEiLCAiQUEiLCAiQUEi4p+pCgrigKJTaG93IEFsbEVxIOKfqCJBQSIsICJBQ0IiLCAiQkIiLCAiQ0Mi4p+pCuKAolNob3cgQXNjIOKfqCJBQSIsICJBQ0IiLCAiQkIiLCAiQ0Mi4p+pCg== Try It!]
Line 610:
<
& (test2=x.~(!arg:? %@?x (%@:~>!x) ?))</
Demonstration
<
. isiZulu
isiXhosa
Line 669:
)
)
</syntaxhighlight>
'''Output'''
<pre>test1 lstA fails
Line 679:
=={{header|C}}==
<
#include <string.h>
Line 698:
return false;
return true;
}</
=={{header|C sharp|C#}}==
{{works with|C sharp|7}}
<
strings.Count < 2 ? (true, true) :
(
strings.Distinct().Count() < 2,
Enumerable.Range(1, strings.Count - 1).All(i => string.Compare(strings[i-1], strings[i]) < 0)
);</
=={{header|C++}}==
Line 714:
{{works with|C++|11}}
<
#include <string>
Line 722:
std::is_sorted( strings.begin(), strings.end(),
[](std::string a, std::string b){ return !(b < a); }) ) // Strictly ascending</
=={{header|Clojure}}==
Used similar approach as the Python solution
<
;; Checks if all items in strings list are equal (returns true if list is empty)
Line 735:
(every? (fn [[a nexta]] (<= (compare a nexta) 0)) (map vector strings (rest strings))))
</syntaxhighlight>
=={{header|COBOL}}==
{{works with|GnuCOBOL}}
<
program-id. CompareLists.
Line 798:
end-if
display " "
.</
{{out}}
<pre>list:
Line 827:
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">
(defun strings-equal-p (strings)
(null (remove (first strings) (rest strings) :test #'string=)))
Line 835:
for string2 in (rest strings)
always (string-lessp string1 string2)))
</syntaxhighlight>
=={{header|D}}==
<
import std.stdio, std.algorithm, std.range, std.string;
Line 847:
writeln;
}
}</
{{out}}
<pre>["AA", "AA", "AA", "AA"]
Line 860:
{{libheader| System.SysUtils}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
program Compare_a_list_of_strings;
Line 928:
readln;
end.</
{{out}}
<pre>[a]
Line 944:
=={{header|Dyalect}}==
<
var prev
for x in xs {
Line 964:
}
true
}</
=={{header|Elena}}==
ELENA 5.0 :
<
import system'routines;
import extensions;
Line 1,005:
console.readChar()
}</
{{out}}
<pre>
Line 1,021:
=={{header|Elixir}}==
<
def compare_strings(strings) do
{length(Enum.uniq(strings))<=1, strict_ascending(strings)}
Line 1,034:
Enum.each(lists, fn list ->
IO.puts "#{inspect RC.compare_strings(list)}\t<= #{inspect list} "
end)</
{{out}}
Line 1,048:
{{trans|Haskell}}
<
-module(compare_strings).
Line 1,061:
all_fulfill(Fun,Strings) ->
lists:all(fun(X) -> X end,lists:zipwith(Fun, lists:droplast(Strings), tl(Strings)) ).
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<
let ascending strings = Seq.isEmpty strings || Seq.forall2 (fun x y -> x < y) strings (Seq.tail strings)</
<p>Actually <code>allEqual</code> is a shortcut and <code>ascending</code> is a general pattern. We can make a function
out of it which constructs a new function from a comparision function</p>
<
<p>and define the 2 task functions that way</p>
<
let ascending = !(<)</
<p>getting something similar as the builtin in Raku</p>
=={{header|Factor}}==
Assuming the list is on top of the data stack, testing for lexical equality:
<
all-equal?</
Testing for ascending order:
<
[ before? ] monotonic?</
=={{header|Forth}}==
Line 1,088:
Raw Forth is a very low level language and has no Native lists so we have to build from scratch.
Remarkably by concatenating these low level operations and using the simple Forth parser we can build the linked lists of strings and the list operators quite simply. The operators and lists that we create become extensions to the language.
<
: ," ( -- ) [CHAR] " WORD c@ 1+ ALLOT ; \ Parse input stream until " and write into next available memory
: [[ ( -- ) 0 C, ; \ begin a list. write a 0 into next memory byte (null string)
Line 1,131:
create strings [[ ," ENTRY 4" ," ENTRY 3" ," ENTRY 2" ," ENTRY 1" ]]
create strings2 [[ ," the same" ," the same" ," the same" ]]
create strings3 [[ ," AAA" ," BBB" ," CCC" ," DDD" ]] </
Test at the Forth console
Line 1,150:
It is better to hide low-level code in general-purpose code-libraries so that the application code can be simple.
Here is my solution using LIST.4TH from my novice-package: http://www.forth.org/novice.html
<
: test-equality ( string node -- new-string bad? )
over count \ -- string node adr cnt
Line 1,164:
seq .line @ seq 2nd 'test find-node
nip 0= ;
</syntaxhighlight>
Here is a test of the above code:
{{out}}
Line 1,188:
On the other hand a function such as ALLINORDER would show the sound of one hand clapping. It would also reveal the order in which comparisons were made, and whether the loop would quit on the first failure or blockheadedly slog on through the lot regardless. Alas, on these questions the documentation for ALL is suspiciously silent.
<syntaxhighlight lang="fortran">
INTEGER MANY,LONG
PARAMETER (LONG = 6,MANY = 4) !Adjust to suit.
Line 1,207:
END IF
END
</
And yes, if MANY is set to one and the extra texts are commented out, the results are both true, and ungrammatical statements are made. Honest. Possibly, another special function, as in <code>COUNT(STRINGS(1:MANY - 1) .LT. STRINGS(2:MANY)))</code> would involve less one-hand-clapping when there are no comparisons to make, but the production of a report that would use it is not in the specification.
Line 1,213:
===F2003-F2008===
F2008 standard ([ISO 2010], 4.4.3) defines the character variable of the character type as a set of values composed of character strings and a character string is a sequence of characters, numbered from left to right 1, 2, 3, ... up to the number of characters in the string. The number of characters in the string is called the length of the string. The length is a type parameter; its kind is processor dependent and its value is greater than or equal to zero. I.e in declaration
<syntaxhighlight lang="fortran">
character (len=12) :: surname
</syntaxhighlight>
keyword len is NOT a size of array, it is an intrinsic parameter of character type, and character type is in fortran a [[first-class type]]: they can be assigned as objects or passed as parameters to a subroutine.
In summary, the character data type in Fortran is a real, first class data type. Fortran character strings are not hacked-up arrays!
<syntaxhighlight lang="fortran">
program compare_char_list
implicit none
Line 1,237:
end if
end program compare_char_list
</syntaxhighlight>
=={{header|FreeBASIC}}==
<
' FB 1.05.0 Win64
Line 1,260:
Return True
End Function
</syntaxhighlight>
=={{header|Fōrmulæ}}==
Line 1,271:
=={{header|Go}}==
<
func AllEqual(strings []string) bool {
Line 1,289:
}
return true
}</
See [[Compare_a_list_of_strings/GoTests]] for validation tests.
Line 1,295:
=={{header|Gosu}}==
<
var isHomogeneous = list.toSet().Count < 2
var isOrderedSet = list.toSet().order().toList() == list</
=={{header|Haskell}}==
<
allEqual xs = and $ zipWith (==) xs (tail xs)
allIncr :: Ord a => [a] -> Bool
allIncr xs = and $ zipWith (<) xs (tail xs)</
Alternatively, using folds:
<
:: Eq a
=> [a] -> Bool
Line 1,320:
=> [a] -> Bool
allIncreasing [] = True
allIncreasing (h:t) = fst $ foldl (\(a, x) y -> (a && x < y, y)) (True, h) t</
or seeking earlier exit (from longer lists) with '''until''', but in fact, perhaps due to lazy execution, the zipWith at the top performs best.
<
:: Eq a
=> [a] -> Bool
Line 1,344:
(\(x, xs) -> null xs || x >= head xs)
(\(_, x:xs) -> (x, xs))
(h, t)</
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon expressions either succeed and return a value (which may be &null) or fail.
<
# list-compare.icn
#
Line 1,390:
}
return
end</
{{out}}
Line 1,402:
=={{header|J}}==
'''Solution''' (''equality test''):<
'''Solution''' (''order test''):<
'''Notes''': <tt>asc</tt> indicates whether <tt>y</tt> is monotonically increasing, but not necessarily strictly monotonically increasing (in other words, it allows equal elements if they are adjacent to each other).
=={{header|Java}}==
{{works with|Java|8}}
<
public class CompareListOfStrings {
Line 1,420:
}
}
}</
{{out}}
<pre>[AA, AA, AA, AA]
Line 1,432:
===ES5===
====Iterative====
<
var out = true, i = 0;
while (++i<a.length) {
Line 1,455:
console.log(azSorted(empty)); // true
console.log(azSorted(single)); // true
</syntaxhighlight>
===ES6===
Line 1,461:
Using a generic zipWith, and functionally composed predicates:
<
'use strict';
Line 1,511:
};
})();</
{{Out}}
<syntaxhighlight lang="javascript">{
"allEqual": [
false,
Line 1,525:
true
]
}</
=={{header|jq}}==
Line 1,532:
For both the following functions, the input is assumed to be a (possibly empty) array of strings.
In both cases also, the implementations are fast but could be improved at the expense of complexity.
<
def lexically_equal:
. as $in
Line 1,542:
. as $in
| reduce range(0;length-1) as $i
(true; if . then $in[$i] < $in[$i + 1] else false end);</
'''Examples''':
<
<
=={{header|Jsish}}==
Code from Javascript, ES5.
<
function allEqual(a) {
var out = true, i = 0;
Line 1,569:
if (allAscending(strings)) puts("strings array in strict ascending order");
else puts("strings array not in strict ascending order");</
{{out}}
Line 1,577:
{{works with|Julia|0.6}}
<
test = [["RC", "RC", "RC"], ["RC", "RC", "Rc"], ["RA", "RB", "RC"],
Line 1,586:
println("The elements are $("not " ^ !allequal(v))all equal.")
println("The elements are $("not " ^ !issorted(v))strictly increasing.")
end</
{{out}}
Line 1,618:
=={{header|Klong}}==
<syntaxhighlight lang="k">
{:[2>#x;1;&/=:'x]}:(["test" "test" "test"])
1
{:[2>#x;1;&/<:'x]}:(["bar" "baz" "foo"])
1
</syntaxhighlight>
=={{header|Kotlin}}==
<
fun areEqual(strings: Array<String>): Boolean {
Line 1,645:
else if (areAscending(args)) println("They are in strictly ascending order")
else println("They are neither equal nor in ascending order")
}</
Sample input/output:
{{out}}
Line 1,654:
=={{header|Lambdatalk}}==
<
{def allsame
{def allsame.r
Line 1,697:
} -> true false false true true
</syntaxhighlight>
=={{header|Lua}}==
<
_, fst = next(t_str)
if fst then
Line 1,739:
check("AA,CC,BB")
check("AA,ACB,BB,CC")
check("single_element")</
{{out}}
<pre>ayu dab dog gar panda tui yak: not identical and ascending.
Line 1,752:
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Function Equal(Strings){
Line 1,792:
}
Checkit
</syntaxhighlight>
=={{header|Maple}}==
<
local i:
for i from 2 to numelems(lst) do
Line 1,811:
tst := ["abc","abc","abc","abc","abc"]:
lexEqual(tst):
lexAscending(tst):</
{{Out|Examples}}
<pre>true
Line 1,821:
This particular version of "Compare a list of strings" was created in Mathcad Prime Express 7.0, a free version of Mathcad Prime 7.0 with restrictions (such as no programming or symbolics). All Mathcad numbers are complex doubles. There is a recursion depth limit of about 4,500. Strings are a distinct data and are not conceptually a list of integers.
<
-- Mathcad vectors are single column arrays.
-- The following notation is for convenience in writing arrays in text form.
Line 1,854:
list:=[11,11,11],[11,22,33],[11,33,22],[33,22,11],[11,132,22,33],[11]]
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
Apply[Equal, data]
OrderedQ[data]</
{{out}}
<pre>False
Line 1,866:
=={{header|MATLAB}} / {{header|Octave}}==
Only the first task is implemented.
<
all(strcmp(alist,alist{1}))</
=={{header|Nanoquery}}==
<
def stringsEqual(stringList)
// if the list is empty, return true
Line 1,906:
// return whether the string were less than each other or not
return lessThan
end</
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
Line 1,955:
return
</syntaxhighlight>
{{out}}
<pre>
Line 1,976:
This is the obvious (and more efficient way) to compare strings in Nim:
<syntaxhighlight lang="nim">
func allEqual(s: openArray[string]): bool =
Line 1,998:
doAssert allEqual(["abc"])
doAssert ascending(["abc"])</
For “allEqual”, there is another simple way using template “allIt” from standard module “sequtils”:
<
func allEqual(s: openArray[string]): bool =
Line 2,009:
doAssert allEqual(["abc", "abc", "abc"])
doAssert not allEqual(["abc", "abd", "abc"])
doAssert allEqual(["abc"])</
There are other less obvious and less efficient ways, using hash sets, sorting or “map” and “zip”.
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">
open List;;
Line 2,044:
List.iter test [lasc;leq;lnoasc];;
</syntaxhighlight>
{{out}}
<pre>
Line 2,069:
=={{header|Oforth}}==
<
: lexCmp(l) l l right( l size 1- ) zipWith(#<) and ;</
=={{header|ooRexx}}==
<
* 28.06.2014 Walter Pachl
*--------------------------------------------------------------------*/
Line 2,104:
Say 'List' name': neither equal nor in increasing order'
End
Return</
{{out}}
<pre>List ABC: elements are in increasing order
Line 2,112:
=={{header|PARI/GP}}==
Easiest is to use <code>Set()</code>:
<
inOrder(strings)=Set(strings)==strings</
More efficient:
<
inOrder(strings)=for(i=2,#strings,if(strings[i]>strings[i-1], return(0))); 1</
=={{header|Perl}}==
<
all { $strings[0] eq $strings[$_] } 1..$#strings # All equal
all { $strings[$_-1] lt $strings[$_] } 1..$#strings # Strictly ascending</
Alternatively, if you can guarantee that the input strings don't contain null bytes, the equality test can be performed by a regex like this:
<
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">allsame</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
Line 2,156:
<span style="color: #000000;">test</span><span style="color: #0000FF;">({</span><span style="color: #008000;">"AA"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ACB"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"BB"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"CC"</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">({</span><span style="color: #008000;">"single_element"</span><span style="color: #0000FF;">})</span>
<!--</
{{out}}
<pre>
Line 2,167:
=={{header|Phixmonti}}==
<
( "alpha" "beta" "gamma" "delta" "epsilon" "zeta"
Line 2,177:
dup len swap 1 get rot repeat == /# put 0 (false) in the pile, indicating that they are not repeated strings #/
</syntaxhighlight>
=={{header|Picat}}==
<
Lists = [["AA","BB","CC"],
["AA","AA","AA"],
Line 2,197:
all_same([A,B|Rest]) :-
A == B,
all_same([B|Rest]).</
{{out}}
Line 2,209:
=={{header|PicoLisp}}==
PicoLisp has the native operators =, > and < these can take an infinite number of arguments and are also able to compare Transient symbols (the Strings of PicoLisp).
<
-> T
(= "AA" "AA" "Aa")
Line 2,220:
-> T
(> "A" "B" "Z" "C")
-> NIL</
If you want a function which takes one list here are some straight-forward implementation:
<syntaxhighlight lang="picolisp">
(de same (List)
(apply = List))
Line 2,234:
(same '("AA" "AA" "AA"))
-> T
</syntaxhighlight>
This would of course also work with <= and >= without any hassle.
=={{header|PL/I}}==
<
/*--------------------------------------------------------------------
* 01.07.2014 Walter Pachl
Line 2,277:
Put Skip List(name!!': '!!txt);
End;
End;</
{{out}}
<pre>ABC: elements are in increasing order
Line 2,284:
=={{header|Plain English}}==
<
If the string things are empty, say yes.
Get a string thing from the string things.
Line 2,302:
If the string thing's string is less than the string thing's previous' string, say no.
Put the string thing's next into the string thing.
Repeat.</
=={{header|PowerShell}}==
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
function IsAscending ( [string[]]$Array ) { ( 0..( $Array.Count - 2 ) ).Where{ $Array[$_] -le $Array[$_+1] }.Count -eq $Array.Count - 1 }
function IsEqual ( [string[]]$Array ) { ( 0..( $Array.Count - 2 ) ).Where{ $Array[$_] -eq $Array[$_+1] }.Count -eq $Array.Count - 1 }
Line 2,317:
IsEqual 'A', 'C', 'B', 'C'
IsEqual 'A', 'A', 'A', 'A'
</syntaxhighlight>
{{out}}
<pre>
Line 2,330:
=={{header|Prolog}}==
<
los(["AA","AA","AA"]).
los(["AA","CC","BB"]).
Line 2,350:
nl.
test :- forall(los(List), test_list(List)).</
{{out}}
<pre>
Line 2,378:
=={{header|PureBasic}}==
<
DataSection
Data.s ~"AA\tAA\tAA\nAA\tBB\tCC\nAA\tCC\tBB\nAA\tACB\tBB\tCC\nsingel_element"
Line 2,415:
PrintN("")
Next
Input()</
{{out}}
<pre>List : AA AA AA
Line 2,440:
A useful pattern is that when you need some function of an item in a list with its next item over possibly all items in the list then <code>f(a, nexta) for a, nexta in zip(alist, alist[1:]))</code> works nicely.
(Especially if an index is not needed elsewhere in the algorithm).
<
all(a < nexta for a, nexta in zip(strings, strings[1:])) # Strictly ascending
len(set(strings)) == 1 # Concise all equal
sorted(strings, reverse=True) == strings # Concise (but not particularly efficient) ascending
</syntaxhighlight>
Line 2,452:
and, if we wish, pass functional forms of standard operators to either of them:
<
Line 2,469:
all(map(lt, az, az[1:]))
)</
{{Out}}
<pre>True False True</pre>
Line 2,479:
The word <code>$></code> compares two strings using the QACSFOT lexical ordering. (QACSFOT - Quackery Arbitrary Character Sequence For Ordered Text. It is less arbitrary than the ASCII sequence.)
<
dup size 1 > while
behead swap
Line 2,493:
[ tuck $> if
[ dip not conclude ] ] ]
drop ] is allinorder ( [ --> b )</
=={{header|R}}==
Line 2,501:
function yields false.
<syntaxhighlight lang="r">
chunks <- function (compare, xs) {
starts = which(c(T, !compare(head(xs, -1), xs[-1]), T))
Line 2,507:
function(i) xs[starts[i]:(starts[i+1]-1)] )
}
</syntaxhighlight>
Testing:
<syntaxhighlight lang="r">
> chunks(`<`, c(0,4,8,1,3,5,7,9))
[[1]]
Line 2,518:
[[2]]
[1] 1 3 5 7 9
</syntaxhighlight>
R displays the results in a very prolix manner, so let's simplify it.
<syntaxhighlight lang="r">
> toString(chunks(`<`, c(0,4,8,1,3,5,7,9,-2,0,88)))
[1] "c(0, 4, 8), c(1, 3, 5, 7, 9), c(-2, 0, 88)"
> toString(chunks(`==`, c(0,0,0,5,5,8)))
[1] "c(0, 0, 0), c(5, 5), 8"
</syntaxhighlight>
Defining the required functions:
<syntaxhighlight lang="r">
all.eq <- function(xs) 1 == length( chunks(`==`, xs))
ascending <- function(xs) 1 == length( chunks(`<`, xs))
</syntaxhighlight>
Testing:
<syntaxhighlight lang="r">
> all.eq(c('by'))
[1] TRUE
Line 2,553:
> ascending(c("at"))
[1] TRUE
</syntaxhighlight>
=={{header|Racket}}==
Line 2,564:
Hence the wrapper in the code below:
<
(define ((list-stringX? stringX?) strs)
(or (null? strs) (null? (cdr strs)) (apply stringX? strs)))
Line 2,585:
(list-string<? '("a" "a")) => #f
(list-string<? '("a" "b" "a")) => #f
(list-string<? '("a" "b" "c")) => #t))</
=={{header|Raku}}==
Line 2,592:
In Raku, putting square brackets around an [[wp:Infix_notation|infix]] operator turns it into a listop that effectively works as if the operator had been but in between all of the elements of the argument list ''(or in technical terms, it [[wp:Fold_(higher-order_function)|folds/reduces]] the list using that operator, while taking into account the operator's inherent [https://design.raku.org/S03.html#Operator_precedence associativity] and identity value)'':
<syntaxhighlight lang="raku"
[lt] @strings # Strictly ascending</
=={{header|Red}}==
<
list1: ["asdf" "Asdf" "asdf"]
Line 2,613:
print all-equal? list3
print sorted? list3
</syntaxhighlight>
{{out}}
<pre>false
Line 2,625:
=={{header|REXX}}==
===version 1===
<
* 28.06.2014 Walter Pachl
*--------------------------------------------------------------------*/
Line 2,667:
Say 'List' value(list)': neither equal nor in increasing order'
End
Return</
{{out}}
<pre>List ABC: elements are in increasing order
Line 2,679:
:::::::* '''parse upper arg x'''
:::::::* '''arg x'''
<
@.1= 'ayu dab dog gar panda tui yak' /*seven strings: they're all ascending.*/
@.2= 'oy oy oy oy oy oy oy oy oy oy' /* ten strings: all equal. */
Line 2,702:
if word(strings,k)<<=word(strings,k-1) then return 0 /*string>prev? */
end /*k*/ /* [↑] 0=false, [↓] 1=true. */
return 1 /*indicate that strings are ascending. */</
{{out|output|text= when using the supplied lists:}}
<pre>
Line 2,728:
===version 3===
This REXX version is more idiomatic.
<
@.1= 'ayu dab dog gar panda tui yak' /*seven strings: they're all ascending.*/
@.2= 'oy oy oy oy oy oy oy oy oy oy' /* ten strings: all equal. */
Line 2,746:
if how=='A' then if word(x,k) <<= word(x,k-1) then return 0 /*≤ prev.?*/
end /*k*/ /* [↓] 1=true. [↑] 0=false. */
return 1 /*indicate strings have true comparison*/</
{{out|output|text= is identical to the above REXX version.}} <br><br>
=={{header|Ruby}}==
<
strings == strings.uniq.sort # ascending?</
Short circuiting:
<
strings.each_cons(2).all?{|str1, str2| str1 < str2} # ascending?</
=={{header|Rust}}==
<
match seq {
&[] | &[_] => true,
Line 2,773:
_ => false
}
}</
=={{header|S-lang}}==
"Simple Loop" and "Array Idiomatic" versions:
<
{
variable n = length(sarr), a0, i;
Line 2,827:
atest(["single_element"]);
atest(NULL);
</syntaxhighlight>
{{out}}
<pre>"AA"
Line 2,865:
=={{header|Scala}}==
Functions implemented in Scala following a functional paradigm
<syntaxhighlight lang="scala">
def strings_are_equal(seq:List[String]):Boolean = seq match {
case Nil => true
Line 2,878:
}
</syntaxhighlight>
{{out}}
<pre>
Line 2,904:
For known lists that are 'short-enough', the simplest solution uses 'apply', but that relies on the list being shorter than the maximum number of arguments a function can accept. Better is to write a simple loop:
<
(define (compare-strings fn strs)
(or (null? strs) ; returns #t on empty list
Line 2,916:
(compare-strings string=? strings) ; test for all equal
(compare-strings string<? strings) ; test for in ascending order
</syntaxhighlight>
=={{header|Seed7}}==
<
const func boolean: allTheSame (in array string: strings) is func
Line 2,945:
end if;
end for;
end func;</
=={{header|SenseTalk}}==
<
analyze ["AA","AA","AA"]
analyze ["AA","CC","BB"]
Line 2,971:
end repeat
return True
end isAscending</
{{Out}}
<pre>
Line 2,993:
=={{header|Sidef}}==
Short-circuiting:
<
1..arr.end -> all{ arr[_-1] < arr[_] } # strictly ascending</
Non short-circuiting:
<
arr == arr.uniq.sort # strictly ascending</
=={{header|Tailspin}}==
Note that we choose here to use 1 as true and 0 as false since Tailspin doesn't (yet?) have booleans
<
// matcher testing if the array contains anything not equal to the first element
templates allEqual
Line 3,026:
otherwise 0 !
end strictEqual
</syntaxhighlight>
=={{header|Tcl}}==
The command form of the <code>eq</code> and <code><</code> operators (introduced in Tcl 8.5) handle arbitrarily many arguments and will check if they're all equal/ordered.
Making the operators work with a list of values is just a matter of using the expansion syntax with them.
<
tcl::mathop::< {*}$strings; # All values in strict order</
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Private Function IsEqualOrAscending(myList) As String
Dim i&, boolEqual As Boolean, boolAsc As Boolean
Line 3,054:
IsEqualOrAscending = "List : " & Join(myList, ",") & ", IsEqual : " & (Not boolEqual) & ", IsAscending : " & Not boolAsc
End Function
</syntaxhighlight>
Call :
<syntaxhighlight lang="vb">
Sub Main()
Dim List
Line 3,068:
Debug.Print IsEqualOrAscending(List)
End Sub
</syntaxhighlight>
{{Out}}
<pre>
Line 3,081:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Function string_compare(arr)
lexical = "Pass"
Line 3,105:
WScript.StdOut.WriteLine string_compare(Array("AA","ACB","BB","CC"))
WScript.StdOut.WriteLine string_compare(Array("FF"))
</syntaxhighlight>
{{Out}}
Line 3,132:
=={{header|Vlang}}==
{{trans|go}}
<
for s in strings {
if s != strings[0] {
Line 3,148:
}
return true
}</
=={{header|Wren}}==
{{libheader|Wren-sort}}
<
var areEqual = Fn.new { |strings|
Line 3,168:
System.print("%(b) are ascending : %(areAscending.call(b))")
System.print("%(c) are all equal : %(areEqual.call(c))")
System.print("%(d) are ascending : %(areAscending.call(d))")</
{{out}}
Line 3,179:
=={{header|XProfan}}==
<
Parameters long liste
var int result = 1
Line 3,227:
ClearList 0
WaitKey
end</
{{out}}
<pre>
Line 3,249:
=={{header|zkl}}==
These short circuit.
<
fcn monoUp(strings){
strings.len()<2 or
strings.reduce(fcn(a,b){ if(a>=b) return(Void.Stop,False); b }).toBool()
}</
<
allEQ(T("AA","AA","AA","AA")).println(); //True
allEQ(T("A", "AA","AA","AA")).println(); //False
Line 3,261:
monoUp(T("a","aa","aaa","aaaa")).println(); //True
monoUp(T("a","aa","aaa","aaa")).println(); //False
monoUp(T("a","b","c","cc")).println(); //True</
=={{header|zonnon}}==
<
module CompareStrings;
type
Line 3,296:
write("ascending?: ");writeln(ascending)
end CompareStrings.
</syntaxhighlight>
=={{header|ZX Spectrum Basic}}==
{{trans|AWK}}
<
20 RESTORE j
30 READ n
Line 3,319:
180 DATA 3,"AA","CC","BB"
190 DATA 4,"AA","ACB","BB","CC"
200 DATA 1,"single_element"</
|