Compare a list of strings: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 26:
=={{header|11l}}==
{{trans|D}}
<langsyntaxhighlight lang="11l">L(strings_s) [‘AA AA AA AA’, ‘AA ACB BB CC’]
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()</langsyntaxhighlight>
 
=={{header|360 Assembly}}==
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
<langsyntaxhighlight lang="360asm">* Compare a list of strings 31/01/2017
COMPLIST CSECT
USING COMPLIST,R13 base register
Line 122:
PG DS CL80
YREGS
END COMPLIST</langsyntaxhighlight>
{{out}}
<pre>
Line 131:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE PTR="CARD"
 
BYTE FUNC AreEqual(PTR ARRAY a BYTE len)
Line 196:
a4(0)="aaa"
Test(a4,1)
RETURN</langsyntaxhighlight>
{{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.
<langsyntaxhighlight Adalang="ada"> package String_Vec is new Ada.Containers.Indefinite_Vectors
(Index_Type => Positive, Element_Type => String);
use type String_Vec.Vector;</langsyntaxhighlight>
 
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.
<langsyntaxhighlight Adalang="ada"> function All_Are_The_Same(Strings: String_Vec.Vector) return Boolean is
begin
for Idx in Strings.First_Index .. Strings.Last_Index-1 loop
Line 237:
end loop;
return True;
end All_Are_The_Same;</langsyntaxhighlight>
 
Similarily, the strictly ascending test checks if Strings(Idx) is greater or equal Strings(Idx+1).
<langsyntaxhighlight Adalang="ada"> function Strictly_Ascending(Strings: String_Vec.Vector) return Boolean is
begin
for Idx in Strings.First_Index+1 .. Strings.Last_Index loop
Line 248:
end loop;
return True;
end Strictly_Ascending;</langsyntaxhighlight>
 
If the variable Strings is of the type String_Vec.vector, one can call these two functions
as usual.
<langsyntaxhighlight Adalang="ada">Put_Line(Boolean'Image(All_Are_The_Same(Strings)) & ", " &
Boolean'Image(Strictly_Ascending(Strings)));</langsyntaxhighlight>
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}}==
<langsyntaxhighlight ALGOL68lang="algol68">[]STRING list1 = ("AA","BB","CC");
[]STRING list2 = ("AA","AA","AA");
[]STRING list3 = ("AA","CC","BB");
Line 298:
print (("...is not in strict ascending order", new line))
FI
OD</langsyntaxhighlight>
{{out}}
<pre>list: AA BB CC
Line 318:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw"> % returns true if all elements of the string array a are equal, false otherwise %
% 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 ;</langsyntaxhighlight>
 
=={{header|AppleScript}}==
Line 361:
 
 
<langsyntaxhighlight AppleScriptlang="applescript">-- allEqual :: [String] -> Bool
on allEqual(xs)
_and(zipWith(my _equal, xs, rest of xs))
Line 469:
end script
end if
end mReturn</langsyntaxhighlight>
 
{{Out}}
Line 476:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">allEqual?: function [lst] -> 1 = size unique lst
ascending?: function [lst] -> lst = sort lst
 
Line 490:
print ["allEqual?" allEqual? l]
print ["ascending?" ascending? l "\n"]
]</langsyntaxhighlight>
 
{{out}}
Line 511:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f COMPARE_A_LIST_OF_STRINGS.AWK
BEGIN {
Line 539:
printf("\n%d\n%d\n",test1,test2)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 567:
 
If all are not equal and the list is invariant under sorting, then it is in ascending order.
<langsyntaxhighlight lang="bqn">AllEq ← ⍋≡⍒
Asc ← ¬∘AllEq∧∧≡⊢
 
Line 574:
 
•Show AllEq ⟨"AA", "ACB", "BB", "CC"⟩
•Show Asc ⟨"AA", "ACB", "BB", "CC"⟩</langsyntaxhighlight>
<langsyntaxhighlight lang="bqn">1
0
0
1</langsyntaxhighlight>
 
[https://mlochbaum.github.io/BQN/try.html#code=QWxsRXEg4oaQIOKNi+KJoeKNkgpBc2Mg4oaQIMKs4oiYQWxsRXHiiKfiiKfiiaHiiqIKCuKAolNob3cgQWxsRXEg4p+oIkFBIiwgIkFBIiwgIkFBIiwgIkFBIuKfqQrigKJTaG93IEFzYyDin6giQUEiLCAiQUEiLCAiQUEiLCAiQUEi4p+pCgrigKJTaG93IEFsbEVxIOKfqCJBQSIsICJBQ0IiLCAiQkIiLCAiQ0Mi4p+pCuKAolNob3cgQXNjIOKfqCJBQSIsICJBQ0IiLCAiQkIiLCAiQ0Mi4p+pCg== Try It!]
Line 610:
 
 
<langsyntaxhighlight Bracmatlang="bracmat"> (test1=first.~(!arg:%@?first ? (%@:~!first) ?))
& (test2=x.~(!arg:? %@?x (%@:~>!x) ?))</langsyntaxhighlight>
 
Demonstration
<langsyntaxhighlight Bracmatlang="bracmat">( ( lstA
. isiZulu
isiXhosa
Line 669:
)
)
</syntaxhighlight>
</lang>
'''Output'''
<pre>test1 lstA fails
Line 679:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdbool.h>
#include <string.h>
 
Line 698:
return false;
return true;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
{{works with|C sharp|7}}
<langsyntaxhighlight lang="csharp">public static (bool lexicallyEqual, bool strictlyAscending) CompareAListOfStrings(List<string> strings) =>
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)
);</langsyntaxhighlight>
 
=={{header|C++}}==
Line 714:
 
{{works with|C++|11}}
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <string>
 
Line 722:
 
std::is_sorted( strings.begin(), strings.end(),
[](std::string a, std::string b){ return !(b < a); }) ) // Strictly ascending</langsyntaxhighlight>
 
=={{header|Clojure}}==
Used similar approach as the Python solution
 
<langsyntaxhighlight lang="clojure">
 
;; 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>
</lang>
 
=={{header|COBOL}}==
{{works with|GnuCOBOL}}
<langsyntaxhighlight lang="cobol"> identification division.
program-id. CompareLists.
 
Line 798:
end-if
display " "
.</langsyntaxhighlight>
{{out}}
<pre>list:
Line 827:
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">
<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>
</lang>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, std.range, std.string;
 
Line 847:
writeln;
}
}</langsyntaxhighlight>
{{out}}
<pre>["AA", "AA", "AA", "AA"]
Line 860:
{{libheader| System.SysUtils}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Compare_a_list_of_strings;
 
Line 928:
 
readln;
end.</langsyntaxhighlight>
{{out}}
<pre>[a]
Line 944:
=={{header|Dyalect}}==
 
<langsyntaxhighlight Dyalectlang="dyalect">func isSorted(xs) {
var prev
for x in xs {
Line 964:
}
true
}</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 5.0 :
<langsyntaxhighlight lang="elena">import system'collections;
import system'routines;
import extensions;
Line 1,005:
console.readChar()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,021:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule RC do
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)</langsyntaxhighlight>
 
{{out}}
Line 1,048:
{{trans|Haskell}}
 
<langsyntaxhighlight lang="erlang">
-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>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let allEqual strings = Seq.isEmpty strings || Seq.forall (fun x -> x = Seq.head strings) (Seq.tail strings)
let ascending strings = Seq.isEmpty strings || Seq.forall2 (fun x y -> x < y) strings (Seq.tail strings)</langsyntaxhighlight>
<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>
<langsyntaxhighlight lang="fsharp">let (!) f s = Seq.isEmpty s || Seq.forall2 f s (Seq.tail s)</langsyntaxhighlight>
<p>and define the 2 task functions that way</p>
<langsyntaxhighlight lang="fsharp">let allEqual = !(=)
let ascending = !(<)</langsyntaxhighlight>
<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:
<langsyntaxhighlight lang="factor">USE: grouping
all-equal?</langsyntaxhighlight>
Testing for ascending order:
<langsyntaxhighlight lang="factor">USING: grouping math.order ;
[ before? ] monotonic?</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="forth">\ linked list of strings creators
: ," ( -- ) [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" ]] </langsyntaxhighlight>
 
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
<langsyntaxhighlight lang="forth">
: 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>
</lang>
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">
<lang Fortran>
INTEGER MANY,LONG
PARAMETER (LONG = 6,MANY = 4) !Adjust to suit.
Line 1,207:
END IF
END
</langsyntaxhighlight>
 
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">
<lang Fortran>
character (len=12) :: surname
</syntaxhighlight>
</lang>
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">
<lang Fortran>
program compare_char_list
implicit none
Line 1,237:
end if
end program compare_char_list
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
' FB 1.05.0 Win64
 
Line 1,260:
Return True
End Function
</syntaxhighlight>
</lang>
 
=={{header|Fōrmulæ}}==
Line 1,271:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package cmp
 
func AllEqual(strings []string) bool {
Line 1,289:
}
return true
}</langsyntaxhighlight>
See [[Compare_a_list_of_strings/GoTests]] for validation tests.
 
Line 1,295:
 
=={{header|Gosu}}==
<langsyntaxhighlight lang="gosu">var list = {"a", "b", "c", "d"}
 
var isHomogeneous = list.toSet().Count < 2
var isOrderedSet = list.toSet().order().toList() == list</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">allEqual :: Eq a => [a] -> Bool
allEqual xs = and $ zipWith (==) xs (tail xs)
allIncr :: Ord a => [a] -> Bool
allIncr xs = and $ zipWith (<) xs (tail xs)</langsyntaxhighlight>
 
 
Alternatively, using folds:
 
<langsyntaxhighlight lang="haskell">allEqual
:: 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</langsyntaxhighlight>
 
or seeking earlier exit (from longer lists) with '''until''', but in fact, perhaps due to lazy execution, the zipWith at the top performs best.
 
<langsyntaxhighlight lang="haskell">allEq
:: Eq a
=> [a] -> Bool
Line 1,344:
(\(x, xs) -> null xs || x >= head xs)
(\(_, x:xs) -> (x, xs))
(h, t)</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon expressions either succeed and return a value (which may be &null) or fail.
 
<langsyntaxhighlight lang="unicon">#
# list-compare.icn
#
Line 1,390:
}
return
end</langsyntaxhighlight>
 
{{out}}
Line 1,402:
=={{header|J}}==
 
'''Solution''' (''equality test''):<langsyntaxhighlight lang="j"> allEq =: 1 = +/@~: NB. or 1 = #@:~. or -: 1&|. or }.-:}:</langsyntaxhighlight>
'''Solution''' (''order test''):<langsyntaxhighlight lang="j"> asc =: /: -: i.@# NB. or -: (/:~) etc.</langsyntaxhighlight>
'''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}}
<langsyntaxhighlight lang="java5">import java.util.Arrays;
 
public class CompareListOfStrings {
Line 1,420:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>[AA, AA, AA, AA]
Line 1,432:
===ES5===
====Iterative====
<langsyntaxhighlight JavaScriptlang="javascript">function allEqual(a) {
var out = true, i = 0;
while (++i<a.length) {
Line 1,455:
console.log(azSorted(empty)); // true
console.log(azSorted(single)); // true
</syntaxhighlight>
</lang>
 
===ES6===
Line 1,461:
 
Using a generic zipWith, and functionally composed predicates:
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,511:
};
 
})();</langsyntaxhighlight>
 
{{Out}}
<syntaxhighlight lang="javascript">{
<lang JavaScript>{
"allEqual": [
false,
Line 1,525:
true
]
}</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="jq"># Are the strings all equal?
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);</langsyntaxhighlight>
'''Examples''':
<langsyntaxhighlight lang="jq">[] | lexically_equal #=> true</langsyntaxhighlight>
<langsyntaxhighlight lang="jq">["a", "ab"] | lexically_ascending #=> true</langsyntaxhighlight>
 
=={{header|Jsish}}==
Code from Javascript, ES5.
 
<langsyntaxhighlight lang="javascript">/* Compare list of strings, in Jsish */
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");</langsyntaxhighlight>
 
{{out}}
Line 1,577:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">allequal(arr::AbstractArray) = isempty(arr) || all(x -> x == first(arr), arr)
 
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</langsyntaxhighlight>
 
{{out}}
Line 1,618:
 
=={{header|Klong}}==
<syntaxhighlight lang="k">
<lang K>
{:[2>#x;1;&/=:'x]}:(["test" "test" "test"])
1
{:[2>#x;1;&/<:'x]}:(["bar" "baz" "foo"])
1
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
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")
}</langsyntaxhighlight>
Sample input/output:
{{out}}
Line 1,654:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{def allsame
{def allsame.r
Line 1,697:
} -> true false false true true
 
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function identical(t_str)
_, fst = next(t_str)
if fst then
Line 1,739:
check("AA,CC,BB")
check("AA,ACB,BB,CC")
check("single_element")</langsyntaxhighlight>
{{out}}
<pre>ayu dab dog gar panda tui yak: not identical and ascending.
Line 1,752:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Function Equal(Strings){
Line 1,792:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">lexEqual := proc(lst)
local i:
for i from 2 to numelems(lst) do
Line 1,811:
tst := ["abc","abc","abc","abc","abc"]:
lexEqual(tst):
lexAscending(tst):</langsyntaxhighlight>
{{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.
 
<langsyntaxhighlight Mathcadlang="mathcad">-- define list of list of strings (nested vector of vectors of strings)
-- 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>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">data1 = {"aaa", "aaa", "aab"};
Apply[Equal, data]
OrderedQ[data]</langsyntaxhighlight>
{{out}}
<pre>False
Line 1,866:
=={{header|MATLAB}} / {{header|Octave}}==
Only the first task is implemented.
<langsyntaxhighlight Matlablang="matlab">alist = {'aa', 'aa', 'aa'}
all(strcmp(alist,alist{1}))</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">// a function to test if a list of strings are equal
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</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,955:
return
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,976:
This is the obvious (and more efficient way) to compare strings in Nim:
 
<syntaxhighlight lang="nim">
<lang Nim>
func allEqual(s: openArray[string]): bool =
 
Line 1,998:
 
doAssert allEqual(["abc"])
doAssert ascending(["abc"])</langsyntaxhighlight>
 
For “allEqual”, there is another simple way using template “allIt” from standard module “sequtils”:
 
<langsyntaxhighlight Nimlang="nim">import sequtils
 
func allEqual(s: openArray[string]): bool =
Line 2,009:
doAssert allEqual(["abc", "abc", "abc"])
doAssert not allEqual(["abc", "abd", "abc"])
doAssert allEqual(["abc"])</langsyntaxhighlight>
 
There are other less obvious and less efficient ways, using hash sets, sorting or “map” and “zip”.
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">
<lang Ocaml>
open List;;
 
Line 2,044:
 
List.iter test [lasc;leq;lnoasc];;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,069:
=={{header|Oforth}}==
 
<langsyntaxhighlight lang="oforth">: lexEqual asSet size 1 <= ;
: lexCmp(l) l l right( l size 1- ) zipWith(#<) and ;</langsyntaxhighlight>
 
=={{header|ooRexx}}==
<langsyntaxhighlight lang="oorexx">/* REXX ---------------------------------------------------------------
* 28.06.2014 Walter Pachl
*--------------------------------------------------------------------*/
Line 2,104:
Say 'List' name': neither equal nor in increasing order'
End
Return</langsyntaxhighlight>
{{out}}
<pre>List ABC: elements are in increasing order
Line 2,112:
=={{header|PARI/GP}}==
Easiest is to use <code>Set()</code>:
<langsyntaxhighlight lang="parigp">allEqual(strings)=#Set(strings)<2
inOrder(strings)=Set(strings)==strings</langsyntaxhighlight>
 
More efficient:
<langsyntaxhighlight lang="parigp">allEqual(strings)=for(i=2,#strings,if(strings[i]!=strings[i-1], return(0))); 1
inOrder(strings)=for(i=2,#strings,if(strings[i]>strings[i-1], return(0))); 1</langsyntaxhighlight>
 
=={{header|Perl}}==
 
<langsyntaxhighlight lang="perl">use List::Util 1.33 qw(all);
 
all { $strings[0] eq $strings[$_] } 1..$#strings # All equal
all { $strings[$_-1] lt $strings[$_] } 1..$#strings # Strictly ascending</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="perl">join("\0", @strings) =~ /^ ( [^\0]*+ ) (?: \0 \1 )* $/x # All equal</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,167:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
( "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>
</lang>
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">main =>
Lists = [["AA","BB","CC"],
["AA","AA","AA"],
Line 2,197:
all_same([A,B|Rest]) :-
A == B,
all_same([B|Rest]).</langsyntaxhighlight>
 
{{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).
<langsyntaxhighlight PicoLisplang="picolisp">(= "AA" "AA" "AA")
-> T
(= "AA" "AA" "Aa")
Line 2,220:
-> T
(> "A" "B" "Z" "C")
-> NIL</langsyntaxhighlight>
If you want a function which takes one list here are some straight-forward implementation:
<syntaxhighlight lang="picolisp">
<lang PicoLisp>
(de same (List)
(apply = List))
Line 2,234:
(same '("AA" "AA" "AA"))
-> T
</syntaxhighlight>
</lang>
This would of course also work with <= and >= without any hassle.
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">*process source xref attributes or(!);
/*--------------------------------------------------------------------
* 01.07.2014 Walter Pachl
Line 2,277:
Put Skip List(name!!': '!!txt);
End;
End;</langsyntaxhighlight>
{{out}}
<pre>ABC: elements are in increasing order
Line 2,284:
 
=={{header|Plain English}}==
<langsyntaxhighlight lang="plainenglish">To decide if some string things are lexically equal:
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.</langsyntaxhighlight>
 
=={{header|PowerShell}}==
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
<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>
</lang>
{{out}}
<pre>
Line 2,330:
 
=={{header|Prolog}}==
<langsyntaxhighlight Prologlang="prolog">los(["AA","BB","CC"]).
los(["AA","AA","AA"]).
los(["AA","CC","BB"]).
Line 2,350:
nl.
 
test :- forall(los(List), test_list(List)).</langsyntaxhighlight>
{{out}}
<pre>
Line 2,378:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">EnableExplicit
DataSection
Data.s ~"AA\tAA\tAA\nAA\tBB\tCC\nAA\tCC\tBB\nAA\tACB\tBB\tCC\nsingel_element"
Line 2,415:
PrintN("")
Next
Input()</langsyntaxhighlight>
{{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).
<langsyntaxhighlight lang="python">all(a == nexta for a, nexta in zip(strings, strings[1:])) # All equal
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>
</lang>
 
 
Line 2,452:
and, if we wish, pass functional forms of standard operators to either of them:
 
<langsyntaxhighlight lang="python">from operator import (eq, lt)
 
 
Line 2,469:
 
all(map(lt, az, az[1:]))
)</langsyntaxhighlight>
{{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.)
 
<langsyntaxhighlight Quackerylang="quackery"> [ [ true swap
dup size 1 > while
behead swap
Line 2,493:
[ tuck $> if
[ dip not conclude ] ] ]
drop ] is allinorder ( [ --> b )</langsyntaxhighlight>
 
=={{header|R}}==
Line 2,501:
function yields false.
 
<syntaxhighlight lang="r">
<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>
</lang>
 
Testing:
 
<syntaxhighlight lang="r">
<lang R>
> chunks(`<`, c(0,4,8,1,3,5,7,9))
[[1]]
Line 2,518:
[[2]]
[1] 1 3 5 7 9
</syntaxhighlight>
</lang>
 
R displays the results in a very prolix manner, so let's simplify it.
 
<syntaxhighlight lang="r">
<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>
</lang>
 
Defining the required functions:
 
<syntaxhighlight lang="r">
<lang R>
all.eq <- function(xs) 1 == length( chunks(`==`, xs))
ascending <- function(xs) 1 == length( chunks(`<`, xs))
</syntaxhighlight>
</lang>
 
Testing:
 
<syntaxhighlight lang="r">
<lang R>
> all.eq(c('by'))
[1] TRUE
Line 2,553:
> ascending(c("at"))
[1] TRUE
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Line 2,564:
 
Hence the wrapper in the code below:
<langsyntaxhighlight lang="racket">#lang racket/base
(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))</langsyntaxhighlight>
 
=={{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" perl6line>[eq] @strings # All equal
[lt] @strings # Strictly ascending</langsyntaxhighlight>
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">Red []
 
list1: ["asdf" "Asdf" "asdf"]
Line 2,613:
print all-equal? list3
print sorted? list3
</syntaxhighlight>
</lang>
{{out}}
<pre>false
Line 2,625:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 28.06.2014 Walter Pachl
*--------------------------------------------------------------------*/
Line 2,667:
Say 'List' value(list)': neither equal nor in increasing order'
End
Return</langsyntaxhighlight>
{{out}}
<pre>List ABC: elements are in increasing order
Line 2,679:
:::::::* '''parse upper arg x'''
:::::::* '''arg x'''
<langsyntaxhighlight lang="rexx">/*REXX program compares a list of (character) strings for: equality, all ascending. */
@.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. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the supplied lists:}}
<pre>
Line 2,728:
===version 3===
This REXX version is more idiomatic.
<langsyntaxhighlight lang="rexx">/*REXX program compares a list of strings for: equality, all ascending. */
@.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*/</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the above REXX version.}} <br><br>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">strings.uniq.one? # all equal?
strings == strings.uniq.sort # ascending?</langsyntaxhighlight>
 
Short circuiting:
<langsyntaxhighlight lang="ruby">strings.all?{|str| str == strings.first} # all equal?
strings.each_cons(2).all?{|str1, str2| str1 < str2} # ascending?</langsyntaxhighlight>
 
=={{header|Rust}}==
 
<langsyntaxhighlight lang="rust">fn strings_are_equal(seq: &[&str]) -> bool {
match seq {
&[] | &[_] => true,
Line 2,773:
_ => false
}
}</langsyntaxhighlight>
 
=={{header|S-lang}}==
"Simple Loop" and "Array Idiomatic" versions:
<langsyntaxhighlight Slang="s-lang">define equal_sl(sarr)
{
variable n = length(sarr), a0, i;
Line 2,827:
atest(["single_element"]);
atest(NULL);
</syntaxhighlight>
</lang>
{{out}}
<pre>"AA"
Line 2,865:
=={{header|Scala}}==
Functions implemented in Scala following a functional paradigm
<syntaxhighlight lang="scala">
<lang Scala>
def strings_are_equal(seq:List[String]):Boolean = seq match {
case Nil => true
Line 2,878:
}
 
</syntaxhighlight>
</lang>
{{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:
 
<langsyntaxhighlight lang="scheme">
(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>
</lang>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func boolean: allTheSame (in array string: strings) is func
Line 2,945:
end if;
end for;
end func;</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">analyze ["AA","BB","CC"]
analyze ["AA","AA","AA"]
analyze ["AA","CC","BB"]
Line 2,971:
end repeat
return True
end isAscending</langsyntaxhighlight>
{{Out}}
<pre>
Line 2,993:
=={{header|Sidef}}==
Short-circuiting:
<langsyntaxhighlight lang="ruby">1..arr.end -> all{ arr[0] == arr[_] } # all equal
1..arr.end -> all{ arr[_-1] < arr[_] } # strictly ascending</langsyntaxhighlight>
 
Non short-circuiting:
<langsyntaxhighlight lang="ruby">arr.uniq.len == 1 # all equal
arr == arr.uniq.sort # strictly ascending</langsyntaxhighlight>
 
=={{header|Tailspin}}==
Note that we choose here to use 1 as true and 0 as false since Tailspin doesn't (yet?) have booleans
<langsyntaxhighlight lang="tailspin">
// matcher testing if the array contains anything not equal to the first element
templates allEqual
Line 3,026:
otherwise 0 !
end strictEqual
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
The command form of the <code>eq</code> and <code>&lt;</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.
<langsyntaxhighlight lang="tcl">tcl::mathop::eq {*}$strings; # All values string-equal
tcl::mathop::< {*}$strings; # All values in strict order</langsyntaxhighlight>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<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>
</lang>
Call :
<syntaxhighlight lang="vb">
<lang vb>
Sub Main()
Dim List
Line 3,068:
Debug.Print IsEqualOrAscending(List)
End Sub
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,081:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<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>
</lang>
 
{{Out}}
Line 3,132:
=={{header|Vlang}}==
{{trans|go}}
<langsyntaxhighlight lang="valng">fn all_equal(strings []string) bool {
for s in strings {
if s != strings[0] {
Line 3,148:
}
return true
}</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|Wren-sort}}
<langsyntaxhighlight lang="ecmascript">import "/sort" for 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))")</langsyntaxhighlight>
 
{{out}}
Line 3,179:
 
=={{header|XProfan}}==
<langsyntaxhighlight XProfanlang="xprofan">Proc allsame
Parameters long liste
var int result = 1
Line 3,227:
ClearList 0
WaitKey
end</langsyntaxhighlight>
{{out}}
<pre>
Line 3,249:
=={{header|zkl}}==
These short circuit.
<langsyntaxhighlight lang="zkl">fcn allEQ(strings){ (not strings.filter1('!=(strings[0]))) }
fcn monoUp(strings){
strings.len()<2 or
strings.reduce(fcn(a,b){ if(a>=b) return(Void.Stop,False); b }).toBool()
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">allEQ(T("AA")).println(); //True
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</langsyntaxhighlight>
 
=={{header|zonnon}}==
<langsyntaxhighlight lang="zonnon">
module CompareStrings;
type
Line 3,296:
write("ascending?: ");writeln(ascending)
end CompareStrings.
</syntaxhighlight>
</lang>
 
=={{header|ZX Spectrum Basic}}==
{{trans|AWK}}
<langsyntaxhighlight lang="zxbasic">10 FOR j=160 TO 200 STEP 10
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"</langsyntaxhighlight>
10,327

edits