Determine if a string is collapsible: Difference between revisions

Content deleted Content added
Razetime (talk | contribs)
add <<<>>>
Thundergnat (talk | contribs)
m syntax highlighting fixup automation
Line 84: Line 84:
{{trans|Kotlin}}
{{trans|Kotlin}}


<lang 11l>F collapse(s)
<syntaxhighlight lang="11l">F collapse(s)
V cs = ‘’
V cs = ‘’
V last = Char("\0")
V last = Char("\0")
Line 108: Line 108:
print(‘original : length = ’s.len‘, string = <<<’s‘>>>’)
print(‘original : length = ’s.len‘, string = <<<’s‘>>>’)
print(‘collapsed : length = ’c.len‘, string = <<<’c‘>>>’)
print(‘collapsed : length = ’c.len‘, string = <<<’c‘>>>’)
print()</lang>
print()</syntaxhighlight>


{{out}}
{{out}}
Line 140: Line 140:
=={{header|8080 Assembly}}==
=={{header|8080 Assembly}}==


<lang 8080asm>bdos: equ 5
<syntaxhighlight lang="8080asm">bdos: equ 5
puts: equ 9
puts: equ 9
org 100h
org 100h
Line 240: Line 240:
db 'and they think it',39,'s hell. $'
db 'and they think it',39,'s hell. $'
str5: db ' '
str5: db ' '
db ' --- Harry S Truman $'</lang>
db ' --- Harry S Truman $'</syntaxhighlight>


{{out}}
{{out}}
Line 257: Line 257:


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC Collapse(CHAR ARRAY in,out)
<syntaxhighlight lang="action!">PROC Collapse(CHAR ARRAY in,out)
BYTE i,j
BYTE i,j
CHAR c
CHAR c
Line 294: Line 294:
Test("I never give 'em hell, I just tell the truth, and they think it's hell. ")
Test("I never give 'em hell, I just tell the truth, and they think it's hell. ")
Test(" --- Harry S Truman ")
Test(" --- Harry S Truman ")
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Determine_if_a_string_is_collapsible.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Determine_if_a_string_is_collapsible.png Screenshot from Atari 8-bit computer]
Line 315: Line 315:


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Collapsible is
procedure Test_Collapsible is
procedure Collapse (S : in String) is
procedure Collapse (S : in String) is
Line 337: Line 337:
Collapse (" --- Harry S Truman ");
Collapse (" --- Harry S Truman ");
end Test_Collapsible;
end Test_Collapsible;
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 352: Line 352:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68>BEGIN
<syntaxhighlight lang="algol68">BEGIN
# returns a collapsed version of s #
# returns a collapsed version of s #
# i.e. s with adjacent duplicate characters removed #
# i.e. s with adjacent duplicate characters removed #
Line 384: Line 384:
OD
OD
END
END
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 402: Line 402:
{{works with|Dyalog APL}}
{{works with|Dyalog APL}}


<lang APL>task←{
<syntaxhighlight lang="apl">task←{
⍝ Collapse a string
⍝ Collapse a string
collapse←{(1,¯1↓⍵≠1⌽⍵)/⍵}
collapse←{(1,¯1↓⍵≠1⌽⍵)/⍵}
Line 428: Line 428:
⍝ Collapse each string and display it as specified
⍝ Collapse each string and display it as specified
↑collapse display¨ strs
↑collapse display¨ strs
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 447: Line 447:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>lines: [
<syntaxhighlight lang="rebol">lines: [
{::}
{::}
{:"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln :}
{:"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln :}
Line 456: Line 456:


loop lines 'line ->
loop lines 'line ->
print squeeze line</lang>
print squeeze line</syntaxhighlight>


{{out}}
{{out}}
Line 467: Line 467:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>collapsible_string(str){
<syntaxhighlight lang="autohotkey">collapsible_string(str){
for i, ch in StrSplit(str){
for i, ch in StrSplit(str){
if (ch <> prev)
if (ch <> prev)
Line 474: Line 474:
}
}
return "original string:`t" StrLen(str) " characters`t«««" str "»»»`nresultant string:`t" StrLen(res) " characters`t«««" res "»»»"
return "original string:`t" StrLen(str) " characters`t«««" str "»»»`nresultant string:`t" StrLen(res) " characters`t«««" res "»»»"
}</lang>
}</syntaxhighlight>
Examples:<lang AutoHotkey>data := [""
Examples:<syntaxhighlight lang="autohotkey">data := [""
, """If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln "
, """If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln "
, "..1111111111111111111111111111111111111111111111111111111111111117777888"
, "..1111111111111111111111111111111111111111111111111111111111111117777888"
Line 482: Line 482:
for i, v in data
for i, v in data
MsgBox % := collapsible_string(v)
MsgBox % := collapsible_string(v)
return</lang>
return</syntaxhighlight>
Outputs:<pre>-----------------------------------------
Outputs:<pre>-----------------------------------------
original string: 0 characters «««»»»
original string: 0 characters «««»»»
Line 501: Line 501:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f DETERMINE_IF_A_STRING_IS_COLLAPSIBLE.AWK
# syntax: GAWK -f DETERMINE_IF_A_STRING_IS_COLLAPSIBLE.AWK
BEGIN {
BEGIN {
Line 532: Line 532:
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 561: Line 561:


=={{header|BaCon}}==
=={{header|BaCon}}==
<lang bacon>DATA ""
<syntaxhighlight lang="bacon">DATA ""
DATA "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "
DATA "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "
DATA "..1111111111111111111111111111111111111111111111111111111111111117777888"
DATA "..1111111111111111111111111111111111111111111111111111111111111117777888"
Line 581: Line 581:
NEXT
NEXT
PRINT ">>> - length: ", found
PRINT ">>> - length: ", found
DONE</lang>
DONE</syntaxhighlight>
{{out}}
{{out}}
<pre><<<>>> - length: 0
<pre><<<>>> - length: 0
Line 600: Line 600:
=={{header|BASIC}}==
=={{header|BASIC}}==


<lang basic>10 READ N%
<syntaxhighlight lang="basic">10 READ N%
20 FOR A% = 1 TO N%
20 FOR A% = 1 TO N%
30 READ I$: GOSUB 100
30 READ I$: GOSUB 100
Line 625: Line 625:
430 DATA "..1111111111111111111111111111111111111111111111111111111111111117777888"
430 DATA "..1111111111111111111111111111111111111111111111111111111111111117777888"
440 DATA "I never give 'em hell, I just tell the truth, and they think it's hell. "
440 DATA "I never give 'em hell, I just tell the truth, and they think it's hell. "
450 DATA " --- Harry S Truman "</lang>
450 DATA " --- Harry S Truman "</syntaxhighlight>


{{out}}
{{out}}
Line 646: Line 646:


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang bcpl>get "libhdr"
<syntaxhighlight lang="bcpl">get "libhdr"


// Collapse a string
// Collapse a string
Line 678: Line 678:
show("I never give 'em hell, I just tell the truth, and they think it's hell. ")
show("I never give 'em hell, I just tell the truth, and they think it's hell. ")
show(" --- Harry S Truman ")
show(" --- Harry S Truman ")
$)</lang>
$)</syntaxhighlight>
{{out}}
{{out}}
<pre>0: <<<>>>
<pre>0: <<<>>>
Line 698: Line 698:
The base function is very simple: Keep adjacent unequal characters, make sure first character is always preserved.
The base function is very simple: Keep adjacent unequal characters, make sure first character is always preserved.


<lang bqn>Collapse←(≠↑1∾1↓≠⟜»)⊸/
<syntaxhighlight lang="bqn">Collapse←(≠↑1∾1↓≠⟜»)⊸/


>{
>{
Line 711: Line 711:
"I never give 'em hell, I just tell the truth, and they think it's hell. "
"I never give 'em hell, I just tell the truth, and they think it's hell. "
" --- Harry S Truman "
" --- Harry S Truman "
⟩</lang><lang>┌─
⟩</syntaxhighlight><syntaxhighlight lang="text">┌─
╵ ┌─
╵ ┌─
╵ 80 "<<<The better the 4-wheel drive, the further you'll be from help when ya get stuck!>>>"
╵ 80 "<<<The better the 4-wheel drive, the further you'll be from help when ya get stuck!>>>"
Line 740: Line 740:
17 "<<< - Hary S Truman >>>"
17 "<<< - Hary S Truman >>>"
┘</lang>
┘</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang Bracmat> ( colapse
<syntaxhighlight lang="bracmat"> ( colapse
= previous
= previous
. str
. str
Line 771: Line 771:
$ "I never give 'em hell, I just tell the truth, and they think it's hell. "
$ "I never give 'em hell, I just tell the truth, and they think it's hell. "
& testcolapse
& testcolapse
$ " --- Harry S Truman "</lang>
$ " --- Harry S Truman "</syntaxhighlight>
'''Output'''
'''Output'''
<pre>«««»»» 0
<pre>«««»»» 0
Line 787: Line 787:
Identical implementation as in [[Determine_if_a_string_is_squeezable]], as both tasks are very similar. The Lincoln quote contains backslashes to accommodate the double quotes via the command line. strcmpi is not part of the C Standard Library, thus comment out the definition in the code if testing on a system where it is already included.
Identical implementation as in [[Determine_if_a_string_is_squeezable]], as both tasks are very similar. The Lincoln quote contains backslashes to accommodate the double quotes via the command line. strcmpi is not part of the C Standard Library, thus comment out the definition in the code if testing on a system where it is already included.


<syntaxhighlight lang="c">
<lang C>
#include<string.h>
#include<string.h>
#include<stdlib.h>
#include<stdlib.h>
Line 958: Line 958:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>
Output :
Output :
<pre>
<pre>
Line 1,012: Line 1,012:


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using static System.Linq.Enumerable;
using static System.Linq.Enumerable;


Line 1,037: Line 1,037:
static string Collapse(string s) => string.IsNullOrEmpty(s) ? "" :
static string Collapse(string s) => string.IsNullOrEmpty(s) ? "" :
s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != s[i - 1]).Select(i => s[i]).ToArray());
s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != s[i - 1]).Select(i => s[i]).ToArray());
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,058: Line 1,058:
=={{header|C++}}==
=={{header|C++}}==
The solution is a straightforward application of the standard library function "unique".
The solution is a straightforward application of the standard library function "unique".
<lang cpp>#include <string>
<syntaxhighlight lang="cpp">#include <string>
#include <iostream>
#include <iostream>
#include <algorithm>
#include <algorithm>
Line 1,083: Line 1,083:
test(" --- Harry S Truman ");
test(" --- Harry S Truman ");
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,104: Line 1,104:


=={{header|Clojure}}==
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
<lang Clojure>
(defn collapse [s]
(defn collapse [s]
(let [runs (partition-by identity s)]
(let [runs (partition-by identity s)]
Line 1,113: Line 1,113:
(str (format "Input: <<<%s>>> (len %d)\n" s (count s))
(str (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)\n" out (count out)))))
(format "becomes: <<<%s>>> (len %d)\n" out (count out)))))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,130: Line 1,130:


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>% Collapse a string
<syntaxhighlight lang="clu">% Collapse a string
collapse = proc (s: string) returns (string)
collapse = proc (s: string) returns (string)
out: array[char] := array[char]$[]
out: array[char] := array[char]$[]
Line 1,173: Line 1,173:
show(ex)
show(ex)
end
end
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>0 <<<>>>
<pre>0 <<<>>>
Line 1,191: Line 1,191:


=={{header|Cowgol}}==
=={{header|Cowgol}}==
<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang="cowgol">include "cowgol.coh";
include "strings.coh";
include "strings.coh";


Line 1,242: Line 1,242:
show(strings[i]);
show(strings[i]);
i := i + 1;
i := i + 1;
end loop;</lang>
end loop;</syntaxhighlight>


{{out}}
{{out}}
Line 1,262: Line 1,262:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


void collapsible(string s) {
void collapsible(string s) {
Line 1,288: Line 1,288:
collapsible(`I never give 'em hell, I just tell the truth, and they think it's hell. `);
collapsible(`I never give 'em hell, I just tell the truth, and they think it's hell. `);
collapsible(` --- Harry S Truman `);
collapsible(` --- Harry S Truman `);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>old: <<<>>>, length = 0
<pre>old: <<<>>>, length = 0
Line 1,307: Line 1,307:
{{libheader| System.SysUtils}}
{{libheader| System.SysUtils}}
{{Trans|D}}
{{Trans|D}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Determine_if_a_string_is_collapsible;
program Determine_if_a_string_is_collapsible;


Line 1,343: Line 1,343:
collapsible(' --- Harry S Truman ');
collapsible(' --- Harry S Truman ');
readln;
readln;
end.</lang>
end.</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang="fsharp">
// Collapse a String. Nigel Galloway: June 9th., 2020
// Collapse a String. Nigel Galloway: June 9th., 2020
//As per the task description a function which 'determines if a character string is collapsible' by testing if any consecutive characters are the same.
//As per the task description a function which 'determines if a character string is collapsible' by testing if any consecutive characters are the same.
Line 1,364: Line 1,364:
collapse " --- Harry S Truman "
collapse " --- Harry S Truman "
collapse "withoutConsecutivelyRepeatedCharacters"
collapse "withoutConsecutivelyRepeatedCharacters"
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,376: Line 1,376:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: formatting io kernel sbufs sequences strings ;
<syntaxhighlight lang="factor">USING: formatting io kernel sbufs sequences strings ;
IN: rosetta-code.string-collapse
IN: rosetta-code.string-collapse


Line 1,404: Line 1,404:
} [ show-collapse ] each ;
} [ show-collapse ] each ;


MAIN: collapse-demo</lang>
MAIN: collapse-demo</syntaxhighlight>
{{out}}
{{out}}
(Using some extra test cases from the Go entry.)
(Using some extra test cases from the Go entry.)
Line 1,439: Line 1,439:
=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
{{trans|BASIC}}
{{trans|BASIC}}
<lang freebasic>Const numCad = 5
<syntaxhighlight lang="freebasic">Const numCad = 5
Data ""
Data ""
Data "'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln "
Data "'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln "
Line 1,469: Line 1,469:
Next j
Next j
Sleep
Sleep
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,494: Line 1,494:


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>collapse[str] := str =~ %s/(.)\1+/$1/g
<syntaxhighlight lang="frink">collapse[str] := str =~ %s/(.)\1+/$1/g


lines = ["",
lines = ["",
Line 1,503: Line 1,503:


for line = lines
for line = lines
println[collapse[line]]</lang>
println[collapse[line]]</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,514: Line 1,514:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,553: Line 1,553:
fmt.Printf("collapsed: length = %2d, string = «««%s»»»\n\n", clen, cs)
fmt.Printf("collapsed: length = %2d, string = «««%s»»»\n\n", clen, cs)
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,586: Line 1,586:
=={{header|Groovy}}==
=={{header|Groovy}}==
{{trans|Java}}
{{trans|Java}}
<lang groovy>class StringCollapsible {
<syntaxhighlight lang="groovy">class StringCollapsible {
static void main(String[] args) {
static void main(String[] args) {
for ( String s : [
for ( String s : [
Line 1,611: Line 1,611:
return sb.toString()
return sb.toString()
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>old: 0 <<<>>>
<pre>old: 0 <<<>>>
Line 1,638: Line 1,638:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Text.Printf (printf)
<syntaxhighlight lang="haskell">import Text.Printf (printf)
import Data.Maybe (catMaybes)
import Data.Maybe (catMaybes)
import Control.Monad (guard)
import Control.Monad (guard)
Line 1,659: Line 1,659:
main =
main =
mapM_ (\(a, b) -> printf "old: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" (length a) a (length b) b)
mapM_ (\(a, b) -> printf "old: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" (length a) a (length b) b)
$ ((,) <*> collapse) <$> input</lang>
$ ((,) <*> collapse) <$> input</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,689: Line 1,689:
Note that we can also directly define a predicate, and a rewrite, in terms of ''Data.List group'',
Note that we can also directly define a predicate, and a rewrite, in terms of ''Data.List group'',


<lang haskell>import Data.List (group)
<syntaxhighlight lang="haskell">import Data.List (group)


isCollapsible :: String -> Bool
isCollapsible :: String -> Bool
Line 1,695: Line 1,695:


collapsed :: String -> String
collapsed :: String -> String
collapsed = map head . group</lang>
collapsed = map head . group</syntaxhighlight>


or, without imports, in terms of pattern matching:
or, without imports, in terms of pattern matching:


<lang haskell>isCollapsible :: String -> Bool
<syntaxhighlight lang="haskell">isCollapsible :: String -> Bool
isCollapsible [] = False
isCollapsible [] = False
isCollapsible [_] = False
isCollapsible [_] = False
Line 1,709: Line 1,709:
collapsed (h:t@(x:_))
collapsed (h:t@(x:_))
| h == x = collapsed t
| h == x = collapsed t
| otherwise = h : collapsed t</lang>
| otherwise = h : collapsed t</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
Line 1,752: Line 1,752:


=={{header|Java}}==
=={{header|Java}}==
<lang java>
<syntaxhighlight lang="java">
// Title: Determine if a string is collapsible
// Title: Determine if a string is collapsible


Line 1,783: Line 1,783:


}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,813: Line 1,813:


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">
<lang javaScript>
String.prototype.collapse = function() {
String.prototype.collapse = function() {
let str = this;
let str = this;
Line 1,835: Line 1,835:
console.log(`«««${col}»»» (${col.length})`);
console.log(`«««${col}»»» (${col.length})`);
}
}
</syntaxhighlight>
</lang>


{{out}} <pre>
{{out}} <pre>
Line 1,852: Line 1,852:
=={{header|jq}}==
=={{header|jq}}==
Here we can use the Unix-like `uniq` function defined on (JSON) arrays to define `collapse` on (JSON) strings:
Here we can use the Unix-like `uniq` function defined on (JSON) arrays to define `collapse` on (JSON) strings:
<lang jq># Input: an array
<syntaxhighlight lang="jq"># Input: an array
# Output: a stream
# Output: a stream
def uniq: foreach .[] as $x ({x:nan, y:.[0]}; {x:$x, y:.x}; select(.x != .y) | .x);
def uniq: foreach .[] as $x ({x:nan, y:.[0]}; {x:$x, y:.x}; select(.x != .y) | .x);


def collapse: explode | [uniq] | implode; </lang>
def collapse: explode | [uniq] | implode; </syntaxhighlight>


The program for the given task can now be written in three lines:
The program for the given task can now be written in three lines:


<lang jq>def Guillemets: "«««\(.)»»»";
<syntaxhighlight lang="jq">def Guillemets: "«««\(.)»»»";


"Original: \(Guillemets) has length \(length)",
"Original: \(Guillemets) has length \(length)",
(collapse | "Collapsed \(Guillemets) has length \(length)")
(collapse | "Collapsed \(Guillemets) has length \(length)")
</syntaxhighlight>
</lang>


Using the following invocation on the five "raw" (i.e. unquoted) strings yields the results as shown:
Using the following invocation on the five "raw" (i.e. unquoted) strings yields the results as shown:
Line 1,870: Line 1,870:
jq -Rrf program.jq raw.txt
jq -Rrf program.jq raw.txt


<lang sh>Original: «««»»» has length 0
<syntaxhighlight lang="sh">Original: «««»»» has length 0
Collapsed «««»»» has length 0
Collapsed «««»»» has length 0
Original: «««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »»» has length 72
Original: «««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »»» has length 72
Line 1,879: Line 1,879:
Collapsed «««I never give 'em hel, I just tel the truth, and they think it's hel. »»» has length 69
Collapsed «««I never give 'em hel, I just tel the truth, and they think it's hel. »»» has length 69
Original: ««« --- Harry S Truman »»» has length 72
Original: ««« --- Harry S Truman »»» has length 72
Collapsed ««« - Hary S Truman »»» has length 17</lang>
Collapsed ««« - Hary S Truman »»» has length 17</syntaxhighlight>




=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>const teststrings = [
<syntaxhighlight lang="julia">const teststrings = [
"",
"",
""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """,
""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """,
Line 1,913: Line 1,913:


testcollapse(teststrings)
testcollapse(teststrings)
</lang>{{out}}
</syntaxhighlight>{{out}}
<pre>
<pre>
«««»»» (length 0)
«««»»» (length 0)
Line 1,936: Line 1,936:
</pre>
</pre>
==== Condensed version: ====
==== Condensed version: ====
<lang julia>const teststrings = [
<syntaxhighlight lang="julia">const teststrings = [
"",
"",
""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """,
""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """,
Line 1,949: Line 1,949:
println("«««$s»»» (length $n)\n collapses to:\n«««$t»»» (length $(length(t))).\n")
println("«««$s»»» (length $n)\n collapses to:\n«««$t»»» (length $(length(t))).\n")
end
end
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Go}}
{{trans|Go}}
<lang scala>fun collapse(s: String): String {
<syntaxhighlight lang="scala">fun collapse(s: String): String {
val cs = StringBuilder()
val cs = StringBuilder()
var last: Char = 0.toChar()
var last: Char = 0.toChar()
Line 1,982: Line 1,982:
println()
println()
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>original : length = 0, string = «««»»»
<pre>original : length = 0, string = «««»»»
Line 2,009: Line 2,009:


=={{header|Ksh}}==
=={{header|Ksh}}==
<lang ksh>
<syntaxhighlight lang="ksh">
#!/bin/ksh
#!/bin/ksh


Line 2,051: Line 2,051:
print ${#strings[i]} "${Guillemet[0]}${strings[i]}${Guillemet[1]}"
print ${#strings[i]} "${Guillemet[0]}${strings[i]}${Guillemet[1]}"
print ${#str} "${Guillemet[0]}${str}${Guillemet[1]}\n"
print ${#str} "${Guillemet[0]}${str}${Guillemet[1]}\n"
done</lang>
done</syntaxhighlight>
{{out}}<pre>0 «««»»»
{{out}}<pre>0 «««»»»
0 «««»»»
0 «««»»»
Line 2,070: Line 2,070:
=={{header|Lua}}==
=={{header|Lua}}==
{{trans|C#}}
{{trans|C#}}
<lang lua>function collapse(s)
<syntaxhighlight lang="lua">function collapse(s)
local ns = ""
local ns = ""
local last = nil
local last = nil
Line 2,103: Line 2,103:
end
end


main()</lang>
main()</syntaxhighlight>
{{out}}
{{out}}
<pre>old: 0 <<<>>>
<pre>old: 0 <<<>>>
Line 2,121: Line 2,121:


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>ClearAll[StringCollapse]
<syntaxhighlight lang="mathematica">ClearAll[StringCollapse]
StringCollapse[s_String] := FixedPoint[StringReplace[y_ ~~ y_ :> y], s]
StringCollapse[s_String] := FixedPoint[StringReplace[y_ ~~ y_ :> y], s]
strings = {"",
strings = {"",
Line 2,135: Line 2,135:
,
,
{s, strings}
{s, strings}
]</lang>
]</syntaxhighlight>
{{out}}
{{out}}
<pre>«««»»»
<pre>«««»»»
Line 2,159: Line 2,159:


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">
<lang Matlab>
function r = collapse(s)
function r = collapse(s)
ix=find((s(1:end-1)==s(2:end))+1;
ix=find((s(1:end-1)==s(2:end))+1;
Line 2,181: Line 2,181:
collapse('║ --- Harry S Truman ║', 'r')
collapse('║ --- Harry S Truman ║', 'r')


</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,213: Line 2,213:


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE StrCollapse;
<syntaxhighlight lang="modula2">MODULE StrCollapse;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
FROM Strings IMPORT Length;
FROM Strings IMPORT Length;
Line 2,257: Line 2,257:
Task("I never give 'em hell, I just tell the truth, and they think it's hell. ");
Task("I never give 'em hell, I just tell the truth, and they think it's hell. ");
Task(" --- Harry S Truman ");
Task(" --- Harry S Truman ");
END StrCollapse.</lang>
END StrCollapse.</syntaxhighlight>
{{out}}
{{out}}
<pre> 0 <<<>>>
<pre> 0 <<<>>>
Line 2,281: Line 2,281:
* On the Interface Pane, in the Command Center, type "demo" and hit enter.
* On the Interface Pane, in the Command Center, type "demo" and hit enter.


<syntaxhighlight lang="netlogo">
<lang NetLogo>
to-report split [ string ]
to-report split [ string ]
;; utility reporter to split a string into a list
;; utility reporter to split a string into a list
Line 2,316: Line 2,316:
demo-collapse
demo-collapse
end
end
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,335: Line 2,335:


=={{header|Nim}}==
=={{header|Nim}}==
<lang Nim>import unicode, strformat
<syntaxhighlight lang="nim">import unicode, strformat


proc collapse(s: string) =
proc collapse(s: string) =
Line 2,362: Line 2,362:


for s in Strings:
for s in Strings:
s.collapse()</lang>
s.collapse()</syntaxhighlight>


{{out}}
{{out}}
Line 2,393: Line 2,393:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>use strict;
<syntaxhighlight lang="perl">use strict;
use warnings;
use warnings;
use utf8;
use utf8;
Line 2,414: Line 2,414:
printf "\nLength: %2d <<<%s>>>\nCollapsible: %s\nLength: %2d <<<%s>>>\n",
printf "\nLength: %2d <<<%s>>>\nCollapsible: %s\nLength: %2d <<<%s>>>\n",
length($_), $_, $_ ne $squish ? 'True' : 'False', length($squish), $squish
length($_), $_, $_ ne $squish ? 'True' : 'False', length($squish), $squish
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Length: 0 <<<>>>
<pre>Length: 0 <<<>>>
Line 2,457: Line 2,457:
If you don't have builtins/punique.e to hand, you may want to take a quick look at squeeze() in
If you don't have builtins/punique.e to hand, you may want to take a quick look at squeeze() in
[[https://rosettacode.org/wiki/Determine_if_a_string_is_squeezable#Phix]], but obviously w/o ch.
[[https://rosettacode.org/wiki/Determine_if_a_string_is_squeezable#Phix]], but obviously w/o ch.
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span>
Line 2,490: Line 2,490:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,513: Line 2,513:
=={{header|PHP}}==
=={{header|PHP}}==


<lang PHP><?php
<syntaxhighlight lang="php"><?php


function collapseString($string) {
function collapseString($string) {
Line 2,554: Line 2,554:
echo 'Collapse : string is not collapsing...', PHP_EOL, PHP_EOL;
echo 'Collapse : string is not collapsing...', PHP_EOL, PHP_EOL;
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,596: Line 2,596:
The <code>COLLAPSE</code> procedure compares bytes and would be fine with any 8-bit input.
The <code>COLLAPSE</code> procedure compares bytes and would be fine with any 8-bit input.


<lang plm>100H:
<syntaxhighlight lang="plm">100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
Line 2,675: Line 2,675:
CALL EXIT;
CALL EXIT;
EOF
EOF
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>0 <<<>>>
<pre>0 <<<>>>
Line 2,693: Line 2,693:


=={{header|Prolog}}==
=={{header|Prolog}}==
<lang prolog>collapse_( [], [] ).
<syntaxhighlight lang="prolog">collapse_( [], [] ).
collapse_( [A], [A] ).
collapse_( [A], [A] ).
collapse_( [A,A|T], R ) :- collapse_( [A|T], R ).
collapse_( [A,A|T], R ) :- collapse_( [A|T], R ).
Line 2,701: Line 2,701:
string_chars( Str, Chars ),
string_chars( Str, Chars ),
collapse_( Chars, Result ),
collapse_( Chars, Result ),
string_chars( Collapsed, Result ).</lang>
string_chars( Collapsed, Result ).</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,739: Line 2,739:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>EnableExplicit
<syntaxhighlight lang="purebasic">EnableExplicit
DataSection
DataSection
STR1:
STR1:
Line 2,774: Line 2,774:
*p_data+StringByteLength(PeekS(*p_data))+2
*p_data+StringByteLength(PeekS(*p_data))+2
Wend
Wend
Input()</lang>
Input()</syntaxhighlight>
{{out}}
{{out}}
<pre>Before collapse: «««»»» (length: 0)
<pre>Before collapse: «««»»» (length: 0)
Line 2,793: Line 2,793:


=={{header|Python}}==
=={{header|Python}}==
<lang python>from itertools import groupby
<syntaxhighlight lang="python">from itertools import groupby


def collapser(txt):
def collapser(txt):
Line 2,815: Line 2,815:
this = "Collapsed"
this = "Collapsed"
sqz = collapser(txt)
sqz = collapser(txt)
print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )</lang>
print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )</syntaxhighlight>


{{out}}
{{out}}
Line 2,848: Line 2,848:
and for the missing predicate, foregrounded in the task title, and already forgotten in the listing of tests:
and for the missing predicate, foregrounded in the task title, and already forgotten in the listing of tests:


<lang python>'''Determining if a string is collapsible'''
<syntaxhighlight lang="python">'''Determining if a string is collapsible'''


from operator import eq
from operator import eq
Line 2,886: Line 2,886:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[False, True, True, True, True, True, True, True, True, False]</pre>
<pre>[False, True, True, True, True, True, True, True, True, False]</pre>
Line 2,892: Line 2,892:
=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ false -1 rot
<syntaxhighlight lang="quackery"> [ false -1 rot
witheach
witheach
[ 2dup = iff
[ 2dup = iff
Line 2,926: Line 2,926:
$ "..1111111111111111111111111111111111111111111111111111111111111117777888" task
$ "..1111111111111111111111111111111111111111111111111111111111111117777888" task
$ "I never give 'em hell, I just tell the truth, and they think it's hell. " task
$ "I never give 'em hell, I just tell the truth, and they think it's hell. " task
$ " --- Harry S Truman " task</lang>
$ " --- Harry S Truman " task</syntaxhighlight>


{{out}}
{{out}}
Line 2,966: Line 2,966:


=={{header|R}}==
=={{header|R}}==
<lang R>collapse_string <- function(string){
<syntaxhighlight lang="r">collapse_string <- function(string){
str_iterable <- strsplit(string, "")[[1]]
str_iterable <- strsplit(string, "")[[1]]
Line 3,008: Line 3,008:
}
}


</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,060: Line 3,060:
=={{header|Racket}}==
=={{header|Racket}}==


<lang Racket>#lang racket
<syntaxhighlight lang="racket">#lang racket


(define (collapse text)
(define (collapse text)
Line 3,087: Line 3,087:
(string-length text) text
(string-length text) text
(string-length collapsed) collapsed))))
(string-length collapsed) collapsed))))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Original (size 0): «««»»»
<pre>Original (size 0): «««»»»
Line 3,122: Line 3,122:
Technically, the task is asking for a boolean. "Determine if a string is collapsible" is answerable with True/False, so return a boolean as well.
Technically, the task is asking for a boolean. "Determine if a string is collapsible" is answerable with True/False, so return a boolean as well.


<lang perl6>map {
<syntaxhighlight lang="raku" line>map {
my $squish = .comb.squish.join;
my $squish = .comb.squish.join;
printf "\nLength: %2d <<<%s>>>\nCollapsible: %s\nLength: %2d <<<%s>>>\n",
printf "\nLength: %2d <<<%s>>>\nCollapsible: %s\nLength: %2d <<<%s>>>\n",
Line 3,139: Line 3,139:
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
STRINGS
STRINGS
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Length: 0 <<<>>>
<pre>Length: 0 <<<>>>
Line 3,179: Line 3,179:


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program "collapses" all immediately repeated characters in a string (or strings).*/
<syntaxhighlight lang="rexx">/*REXX program "collapses" all immediately repeated characters in a string (or strings).*/
@.= /*define a default for the @. array. */
@.= /*define a default for the @. array. */
parse arg x /*obtain optional argument from the CL.*/
parse arg x /*obtain optional argument from the CL.*/
Line 3,207: Line 3,207:
$= $ || _ /*append the character, it's different.*/
$= $ || _ /*append the character, it's different.*/
end /*j*/
end /*j*/
collapsible= y\==$; return $ /*set boolean to true if collapsible.*/</lang>
collapsible= y\==$; return $ /*set boolean to true if collapsible.*/</syntaxhighlight>
{{out|output|text=&nbsp; when using the internal default inputs:}}
{{out|output|text=&nbsp; when using the internal default inputs:}}
<pre>
<pre>
Line 3,234: Line 3,234:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
load "stdlib.ring"
load "stdlib.ring"


Line 3,261: Line 3,261:


see "done..." + nl
see "done..." + nl
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 3,280: Line 3,280:
=={{header|Ruby}}==
=={{header|Ruby}}==
This is built in since at least a decade under the method name 'squeeze'. squeeze(" ") would only squeeze spaces.
This is built in since at least a decade under the method name 'squeeze'. squeeze(" ") would only squeeze spaces.
<lang ruby>strings = ["",
<syntaxhighlight lang="ruby">strings = ["",
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
Line 3,296: Line 3,296:
puts
puts
end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>«««»»» (size 0)
<pre>«««»»» (size 0)
Line 3,327: Line 3,327:


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>fn collapse_string(val: &str) -> String {
<syntaxhighlight lang="rust">fn collapse_string(val: &str) -> String {
let mut output = String::new();
let mut output = String::new();
let mut chars = val.chars().peekable();
let mut chars = val.chars().peekable();
Line 3,365: Line 3,365:
println!();
println!();
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,396: Line 3,396:
===Pure imperative programming 😃===
===Pure imperative programming 😃===


<lang Scala>object CollapsibleString {
<syntaxhighlight lang="scala">object CollapsibleString {


/**Collapse a string (if possible)*/
/**Collapse a string (if possible)*/
Line 3,449: Line 3,449:




}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>ORIGINAL : length = 0, string = «««»»»
<pre>ORIGINAL : length = 0, string = «««»»»
Line 3,484: Line 3,484:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func squeeze(str) {
<syntaxhighlight lang="ruby">func squeeze(str) {
str.gsub(/(.)\1+/, {|s1| s1 })
str.gsub(/(.)\1+/, {|s1| s1 })
}
}
Line 3,502: Line 3,502:
say "«««#{str}»»» (length: #{str.len})"
say "«««#{str}»»» (length: #{str.len})"
say "«««#{ssq}»»» (length: #{ssq.len})\n"
say "«««#{ssq}»»» (length: #{ssq.len})\n"
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre style="font-size: 80%">
<pre style="font-size: 80%">
Line 3,535: Line 3,535:
=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
{{works with|Smalltalk/X}}
<lang smalltalk>#(
<syntaxhighlight lang="smalltalk">#(
'The better the 4-wheel drive, the further you''ll be from help when ya get stuck!'
'The better the 4-wheel drive, the further you''ll be from help when ya get stuck!'
'headmistressship'
'headmistressship'
Line 3,553: Line 3,553:
showCR:( eachWord,'(length:',eachWord size,')' );
showCR:( eachWord,'(length:',eachWord size,')' );
showCR:( shortened,'(length:',shortened size,')' ).
showCR:( shortened,'(length:',shortened size,')' ).
]</lang>
]</syntaxhighlight>
{{out}}
{{out}}
<pre>The better the 4-wheel drive, the further you'll be from help when ya get stuck!(length:80)
<pre>The better the 4-wheel drive, the further you'll be from help when ya get stuck!(length:80)
Line 3,565: Line 3,565:


=={{header|Swift}}==
=={{header|Swift}}==
<lang Swift>let strings = [
<syntaxhighlight lang="swift">let strings = [
"",
"",
#""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln "#,
#""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln "#,
Line 3,581: Line 3,581:
for (original, collapsed) in zip(strings, collapsedStrings) {
for (original, collapsed) in zip(strings, collapsedStrings) {
print (String(format: "%03d «%@»\n%03d «%@»\n", original.count, original, collapsed.count, collapsed))
print (String(format: "%03d «%@»\n%03d «%@»\n", original.count, original, collapsed.count, collapsed))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,615: Line 3,615:
=={{header|Tcl}}==
=={{header|Tcl}}==
Please note the ;# ' comments, there appears to be a syntax hightlighting bug with RC
Please note the ;# ' comments, there appears to be a syntax hightlighting bug with RC
<lang tcl>set test {
<syntaxhighlight lang="tcl">set test {
{}
{}
{"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln }
{"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln }
Line 3,634: Line 3,634:
puts ----------------------
puts ----------------------
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,662: Line 3,662:
=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|C#}}
{{trans|C#}}
<lang vbnet>Module Module1
<syntaxhighlight lang="vbnet">Module Module1


Function Collapse(s As String) As String
Function Collapse(s As String) As String
Line 3,688: Line 3,688:
End Sub
End Sub


End Module</lang>
End Module</syntaxhighlight>
{{out}}
{{out}}
<pre>old: 0 «««»»»
<pre>old: 0 «««»»»
Line 3,707: Line 3,707:
=={{header|VBA}}==
=={{header|VBA}}==
Function :
Function :
<lang vb>Function Collapse(strIn As String) As String
<syntaxhighlight lang="vb">Function Collapse(strIn As String) As String
Dim i As Long, strOut As String
Dim i As Long, strOut As String
If Len(strIn) > 0 Then
If Len(strIn) > 0 Then
Line 3,718: Line 3,718:
End If
End If
Collapse = strOut
Collapse = strOut
End Function</lang>
End Function</syntaxhighlight>
To Call :
To Call :
<lang vb>Sub CallCollapse()
<syntaxhighlight lang="vb">Sub CallCollapse()
Dim S As String
Dim S As String
S = vbNullString
S = vbNullString
Line 3,737: Line 3,737:
Debug.Print "String : <<<" & S & ">>>", "Lenght : " & Len(S)
Debug.Print "String : <<<" & S & ">>>", "Lenght : " & Len(S)
Debug.Print "Collapsed : <<<" & Collapse(S) & ">>>", "Lenght : " & Len(Collapse(S))
Debug.Print "Collapsed : <<<" & Collapse(S) & ">>>", "Lenght : " & Len(Collapse(S))
End Sub</lang>
End Sub</syntaxhighlight>
{{out}}
{{out}}
<pre>String : <<<>>> Lenght : 0
<pre>String : <<<>>> Lenght : 0
Line 3,752: Line 3,752:
=={{header|Vlang}}==
=={{header|Vlang}}==
{{trans|Go}}
{{trans|Go}}
<lang vlang>// Returns collapsed string, original and new lengths in
<syntaxhighlight lang="vlang">// Returns collapsed string, original and new lengths in
// unicode code points (not normalized).
// unicode code points (not normalized).
fn collapse(s string) (string, int, int) {
fn collapse(s string) (string, int, int) {
Line 3,787: Line 3,787:
println("collapsed: length = ${clen:2}, string = «««$cs»»»\n")
println("collapsed: length = ${clen:2}, string = «««$cs»»»\n")
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,822: Line 3,822:
{{trans|Go}}
{{trans|Go}}
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "/fmt" for Fmt
<syntaxhighlight lang="ecmascript">import "/fmt" for Fmt


// Returns collapsed string, original and new lengths in
// Returns collapsed string, original and new lengths in
Line 3,853: Line 3,853:
System.print("original : length = %(Fmt.d(2, r[1])), string = «««%(s)»»»")
System.print("original : length = %(Fmt.d(2, r[1])), string = «««%(s)»»»")
System.print("collapsed: length = %(Fmt.d(2, r[2])), string = «««%(r[0])»»»\n")
System.print("collapsed: length = %(Fmt.d(2, r[2])), string = «««%(r[0])»»»\n")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,886: Line 3,886:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>string 0;
<syntaxhighlight lang="xpl0">string 0;
char C, I, J, Last;
char C, I, J, Last;


Line 3,915: Line 3,915:
Text(0, "<<<"); Text(0, C); Text(0, ">>> "); IntOut(0, J); CrLf(0);
Text(0, "<<<"); Text(0, C); Text(0, ">>> "); IntOut(0, J); CrLf(0);
];
];
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 3,932: Line 3,932:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn collapsible(str){ // no Unicode
<syntaxhighlight lang="zkl">fcn collapsible(str){ // no Unicode
sink:=Sink(String);
sink:=Sink(String);
str.reduce('wrap(c1,c2){ if(c1!=c2) sink.write(c2); c2 },""); // prime with \0
str.reduce('wrap(c1,c2){ if(c1!=c2) sink.write(c2); c2 },""); // prime with \0
cstr:=sink.close();
cstr:=sink.close();
return(str.len()!=cstr.len(), cstr);
return(str.len()!=cstr.len(), cstr);
}</lang>
}</syntaxhighlight>
<lang zkl>strings:=
<syntaxhighlight lang="zkl">strings:=
0'^
0'^
"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln
"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln
Line 3,956: Line 3,956:
_,cstr:=collapsible(s);
_,cstr:=collapsible(s);
println("After: %3d >>>%s<<<\n".fmt(cstr.len(),cstr));
println("After: %3d >>>%s<<<\n".fmt(cstr.len(),cstr));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>