Abbreviations, simple: Difference between revisions

→‎{{header|REXX}}: ooRexx conformance and readabie
(→‎{{header|ARM Assembly}}: flaged as needed improvement.)
(→‎{{header|REXX}}: ooRexx conformance and readabie)
 
(34 intermediate revisions by 20 users not shown)
Line 90:
{{Template:Strings}}
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V command_table_text =
|‘add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1’
 
V user_words = ‘riG rePEAT copies put mo rest types fup. 6 poweRin’
 
F find_abbreviations_length(command_table_text)
‘ find the minimal abbreviation length for each word.
a word that does not have minimum abbreviation length specified
gets it's full lengths as the minimum.
[String = Int] command_table
V input_list = command_table_text.split((‘ ’, "\n"), group_delimiters' 1B)
V i = 0
 
V word = ‘’
L i < input_list.len | word != ‘’
I word == ‘’
word = input_list[i++]
V abbr_len = I i < input_list.len {input_list[i++]} E String(word.len)
X.try
command_table[word] = Int(abbr_len)
word = ‘’
X.catch ValueError
command_table[word] = word.len
word = abbr_len
R command_table
 
F find_abbreviations(command_table)
‘ for each command insert all possible abbreviations’
[String = String] abbreviations
L(command, min_abbr_len) command_table
L(l) min_abbr_len .. command.len
V abbr = command[0 .< l].lowercase()
abbreviations[abbr] = command.uppercase()
R abbreviations
 
F parse_user_string(user_string, abbreviations)
V user_words = user_string.split(‘ ’, group_delimiters' 1B).map(word -> word.lowercase())
V commands = user_words.map(user_word -> @abbreviations.get(user_word, ‘*error*’))
R commands.join(‘ ’)
 
V command_table = find_abbreviations_length(command_table_text)
V abbreviations_table = find_abbreviations(command_table)
 
V full_words = parse_user_string(user_words, abbreviations_table)
 
print(‘user words: ’user_words)
print(‘full words: ’full_words)</syntaxhighlight>
 
{{out}}
<pre>
user words: riG rePEAT copies put mo rest types fup. 6 poweRin
full words: RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
</pre>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program abbrSimple64.s */
Line 217 ⟶ 283:
ldr x5,[x6,#command_min]
cmp x5,#0 // minimum = zéro ?
ble 4f2f
cmp x4,x5 // input < command capital letters
blt 4f // no correct
add x3,x3,#1 // else increment counter
mov x7,x1 // and save address command
b 4f
2:
mov x0,x1
bl computeLength // length table command
cmp x0,x4 // length input commant <> lenght table command
bne 4f // no correct
add x3,x3,#1 // else increment counter
mov x7,x1 // and save address command
Line 513 ⟶ 587:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
<pre>
Enter command (or <ctrl-c> to stop) : riG
Line 522 ⟶ 596:
*error*
Enter command (or <ctrl-c> to stop) : put
PUT
*error*
Enter command (or <ctrl-c> to stop) : mo
MOVE
Line 538 ⟶ 612:
pi@debian-buster-64:~/asm64/rosetta/asm9 $
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Characters.Handling;
with Ada.Containers.Vectors;
with Ada.Strings.Fixed;
with Ada.Strings.Maps.Constants;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
 
procedure Abbreviations_Simple is
 
use Ada.Strings.Unbounded;
subtype Ustring is Unbounded_String;
 
type Word_Entry is record
Word : Ustring;
Min : Natural;
end record;
 
package Command_Vectors
is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Word_Entry);
 
Commands : Command_Vectors.Vector;
Last_Word : Ustring;
Last_Was_Word : Boolean := False;
 
procedure Append (Word_List : String) is
use Ada.Strings;
 
function Is_Word (Item : String) return Boolean
is (Fixed.Count (Item, Maps.Constants.Letter_Set) /= 0);
 
procedure Process (Token : String) is
begin
if Is_Word (Token) then
if Last_Was_Word then
Commands.Append ((Word => Last_Word,
Min => Length (Last_Word)));
end if;
Last_Word := To_Unbounded_String (Token);
Last_Was_Word := True;
 
else -- Token is expected to be decimal
Commands.Append ((Word => Last_Word,
Min => Natural'Value (Token)));
Last_Was_Word := False;
end if;
end Process;
 
Token_First : Positive := Word_List'First;
Token_Last : Natural;
begin
while Token_First in Word_List'Range loop
 
Fixed.Find_Token (Word_List, Maps.Constants.Alphanumeric_Set,
Token_First, Inside,
Token_First, Token_Last);
exit when Token_Last = 0;
 
Process (Word_List (Token_First .. Token_Last));
 
Token_First := Token_Last + 1;
end loop;
end Append;
 
function Match (Word : String) return String is
use Ada.Characters.Handling;
use Ada.Strings.Fixed;
Result : Ustring := To_Unbounded_String ("*error*");
Min : Natural := 0;
Upper_Word : constant String := To_Upper (Word);
begin
if Upper_Word = "" then
return "";
end if;
 
for Candidate of Commands loop
declare
Upper_Cand : constant String := To_Upper (To_String (Candidate.Word));
Length : constant Natural := Natural'Max (Candidate.Min,
Upper_Word'Length);
Upper_Abbrev_Cand : constant String := Head (Upper_Cand, Length);
Upper_Abbrev_Word : constant String := Head (Upper_Word, Length);
begin
if Upper_Word = Upper_Cand
and then Upper_Word'Length > Min
then
Result := To_Unbounded_String (Upper_Cand);
Min := Upper_Word'Length;
elsif Upper_Abbrev_Word = Upper_Abbrev_Cand
and then Upper_Abbrev_Word'Length > Min
then
Result := To_Unbounded_String (Upper_Cand);
Min := Upper_Abbrev_Word'Length;
end if;
end;
end loop;
return To_String (Result);
end Match;
 
procedure Put_Match (To : String) is
use Ada.Text_IO;
begin
Put ("Match to '"); Put (To);
Put ("' is '"); Put (Match (To));
Put_Line ("'");
end Put_Match;
 
procedure A (Item : String) renames Append;
begin
A ("add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3");
A ("compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate");
A ("3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2");
A ("forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load");
A ("locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2");
A ("msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3");
A ("refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left");
A ("2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1");
 
Put_Match ("riG");
Put_Match ("rePEAT");
Put_Match ("copies");
Put_Match ("put");
Put_Match ("mo");
Put_Match ("rest");
Put_Match ("types");
Put_Match ("fup.");
Put_Match ("6");
Put_Match ("poweRin");
Put_Match ("");
end Abbreviations_Simple;</syntaxhighlight>
 
{{out}}
<pre>
Match to 'riG' is 'RIGHT'
Match to 'rePEAT' is 'REPEAT'
Match to 'copies' is '*error*'
Match to 'put' is 'PUT'
Match to 'mo' is 'MOVE'
Match to 'rest' is 'RESTORE'
Match to 'types' is '*error*'
Match to 'fup.' is '*error*'
Match to '6' is '*error*'
Match to 'poweRin' is 'POWERINPUT'
Match to '' is ''
</pre>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
<langsyntaxhighlight lang="algol68"># "Simple" abbreviations #
 
# returns the next word from text, updating pos #
Line 669 ⟶ 891:
 
# task test cases #
test expand( "riG rePEAT copies put mo rest types fup. 6 poweRin" )</langsyntaxhighlight>
{{out}}
<pre>
Line 683 ⟶ 905:
Also note that &nbsp; <big> put </big> &nbsp; isn't an error. }}
 
<pre> Ok correction le 17/11/2020 16H </pre>
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program abbrSimple.s */
/* store list of command in a file */
/* and run the program abbrEasyabbrSimple command.file */
 
/* REMARK 1 : this program use routines in a include file
Line 820 ⟶ 1,043:
ldr r5,[r6,#command_min]
cmp r5,#0 @ minimum = zéro ?
ble 4f2f
cmp r4,r5 @ input < command capitalminimum letters
blt 4f @ no correct
add r3,r3,#1 @ else increment counter
mov r7,r1 @ and save address command
b 4f
2:
mov r0,r1
bl computeLength @ length input command
cmp r4,r0 @ length command input = length command
bne 4f @ no correct
add r3,r3,#1 @ else increment counter
mov r7,r1 @ and save address command
Line 1,086 ⟶ 1,317:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
</lang>
<pre>
Enter command (or <ctrl-c> to stop) : riG
Line 1,095 ⟶ 1,326:
*error*
Enter command (or <ctrl-c> to stop) : put
PUT
*error*
Enter command (or <ctrl-c> to stop) : mo
MOVE
Line 1,106 ⟶ 1,337:
Enter command (or <ctrl-c> to stop) : 6
*error*
Enter command (or <ctrl-c> to stop) : poxeRinpoweRin
POWERINPUT
*error*
Enter command (or <ctrl-c> to stop) : ^C
pi@raspberrypi:~/asm32/rosetta32/ass9 $
</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">table := "
(
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
)"
 
MsgBox % result := Abbreviations("riG rePEAT copies put mo rest types fup. 6 poweRin", table)
return
 
Abbreviations(str, table){
Words := [], Expanded := []
while pos := RegExMatch(table, "i)([a-z]+)(?:\s+(\d+))?", m, A_Index=1?1:pos+StrLen(m))
Words[m1] := m2?m2:StrLen(m1)
for i, abb in StrSplit(RegExReplace(str, " +", " "), " ")
{
for word, count in Words
if (word ~= "i)^" abb) && (StrLen(abb) >= count)
{
StringUpper, word, word
result .= word " "
Expanded[abb] := true
break
}
if !Expanded[abb]
result .= "*error* "
}
return Trim(result, " ")
}</syntaxhighlight>
{{out}}
<pre>RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
Line 1,262 ⟶ 1,530:
free_command_list(commands);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 1,271 ⟶ 1,539:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <cctype>
#include <iostream>
Line 1,387 ⟶ 1,655:
std::cout << "output: " << output << '\n';
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 1,394 ⟶ 1,662:
output: RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
</pre>
 
=={{header|Clojure}}==
NOTE: Type Hints have been added here to indicate the types of function arguments and to make the program faster. They are not strictly necessary, since Clojure is a dynamically typed language (i.e., variable types are determined at runtime).
 
<syntaxhighlight lang="clojure">
(defn words
"Split string into words"
[^String str]
(.split (.stripLeading str) "\\s+"))
 
(defn join-words
"Join words into a single string"
^String [strings]
(String/join " " strings))
 
;; SOURCE: https://www.stackoverflow.com/a/38947571/12947681
(defn starts-with-ignore-case
"Does string start with prefix (ignoring case)?"
^Boolean [^String string, ^String prefix]
(.regionMatches string true 0 prefix 0 (count prefix)))
 
(defrecord CommandWord [^String word, ^long min-abbr-size])
 
(defn parse-cmd-table
"Parse list of strings in command table into list of words and numbers
If number is missing for any word, then the word is not included"
([cmd-table]
(parse-cmd-table cmd-table 0 []))
([cmd-table i ans]
(let [cmd-count (count cmd-table)]
(if (= i cmd-count)
ans
(let [word (nth cmd-table i),
[i num] (try [(+ i 2)
(Integer/parseInt ^String (nth cmd-table (inc i)))]
(catch NumberFormatException _
[(inc i) 0]))]
(recur cmd-table i (conj ans (CommandWord. word num))))))))
 
;; cmd-table is a list of objects of type CommandWord (defined above)
(def cmd-table
(->
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"
words
parse-cmd-table))
 
(defn abbr?
"Is abbr a valid abbreviation of this command?"
^Boolean [^String abbr, ^CommandWord cmd]
(let [{:keys [word min-abbr-size]} cmd]
(and (<= min-abbr-size (count abbr) (count word))
(starts-with-ignore-case word abbr))))
 
(defn solution
"Find word matching each abbreviation in input (or *error* if not found),
and join results into a string"
^String [^String str]
(join-words (for [abbr (words str)]
(if-let [{:keys [word]} (first (filter #(abbr? abbr %) cmd-table))]
(.toUpperCase ^String word)
"*error*"))))
 
;; Print solution for given test case
(println (solution "riG rePEAT copies put mo rest types fup. 6 poweRin"))
</syntaxhighlight>
 
{{out}}
<pre>RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT</pre>
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="crystal">COMMAND_TABLE =
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
Line 1,447 ⟶ 1,790:
puts "Output:"
puts parse_user_input(user_input, cmds)
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,458 ⟶ 1,801:
 
=={{header|D}}==
<langsyntaxhighlight Dlang="d">class Abbreviations
{
import std.array: split, join;
Line 1,521 ⟶ 1,864:
writeln("Output: ", new Abbreviations(table).expand(input));
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,527 ⟶ 1,870:
Output: RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
</pre>
=={{header|Delphi}}==
 
{{output?}}
 
{{libheader| System.SysUtils}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
program Abraviation_simple;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils;
 
type
TCommand = record
value: string;
len: integer;
end;
 
function ReadTable(table: string): TArray<TCommand>;
begin
var fields := table.Split([' '], TStringSplitOptions.ExcludeEmpty);
var i := 0;
var max := Length(fields);
while i < max do
begin
var cmd := fields[i];
var cmdLen := cmd.Length;
inc(i);
 
if i < max then
begin
var num: Integer;
if TryStrToInt(fields[i], num) and (1 <= num) and (num < cmdLen) then
begin
cmdLen := num;
inc(i);
end;
end;
 
SetLength(result, Length(result) + 1);
with result[High(result)] do
begin
value := cmd;
len := cmdLen;
end;
end;
end;
 
function ValidateCommands(Commands: TArray<TCommand>; Words: TArray<string>):
TArray<string>;
begin
SetLength(result, 0);
for var wd in Words do
begin
var matchFound := false;
var wLen := wd.Length;
for var i := 0 to High(Commands) do
begin
var command := Commands[i];
if (command.len = 0) or (wLen < command.len) or (wLen > command.value.Length) then
Continue;
var c := command.value.ToUpper;
var w := wd.ToUpper;
if c.StartsWith(w) then
begin
SetLength(result, Length(result) + 1);
result[High(result)] := c;
matchFound := true;
Break;
end;
end;
if not matchFound then
begin
SetLength(result, Length(result) + 1);
result[High(result)] := '*error*';
end;
end;
end;
 
procedure PrintResults(words, results: TArray<string>);
begin
Writeln('user words:');
for var w in words do
write(^I, w);
Writeln(#10, 'full words:'^I, string.join(^I, results));
end;
 
const
table = '' +
'add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 ' +
'compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate ' +
'3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 ' +
'forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load ' +
'locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 ' +
'msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 ' +
'refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left ' +
'2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 ';
 
const
SENTENCE = 'riG rePEAT copies put mo rest types fup. 6 poweRin';
 
begin
var Commands := ReadTable(table);
var Words := SENTENCE.Split([' '], TStringSplitOptions.ExcludeEmpty);
 
var results := ValidateCommands(Commands, Words);
 
PrintResults(Words, results);
 
Readln;
end.</syntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: arrays assocs combinators formatting fry grouping.extras
kernel literals math math.parser multiline sequences
splitting.extras unicode ;
Line 1,592 ⟶ 2,048:
: main ( -- ) input "" [ show-commands ] bi@ ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 1,607 ⟶ 2,063:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
<langsyntaxhighlight lang="forth">include FMS-SI.f
include FMS-SILib.f
 
Line 1,662 ⟶ 2,118:
run RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT ok
 
</syntaxhighlight>
</lang>
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">_window = 1
begin enum 1
_userStringFld
_validateBtn
_resultsStringFld
end enum
 
void local fn BuildWindow
window _window, @"Abbreviations, simple", (0,0,600,268)
WindowSetContentMinSize( _window, fn CGSizeMake( 200, 268 ) )
WindowSetContentMaxSize( _window, fn CGSizeMake( 10000, 268 ) )
textfield _userStringFld,, @"riG rePEAT copies put mo rest types fup. 6 poweRin", (20,152,560,96)
TextFieldSetPlaceholderString( _userStringFld, @"Enter commands" )
ViewSetAutoresizingMask( _userStringFld, NSViewWidthSizable )
button _validateBtn,,, @"Validate", (259,117,83,32)
ViewSetAutoresizingMask( _validateBtn, NSViewMinXMargin + NSViewMaxXMargin )
textfield _resultsStringFld,,, (20,20,560,96)
TextFieldSetEditable( _resultsStringFld, NO )
TextFieldSetSelectable( _resultsStringFld, YES )
ViewSetAutoresizingMask( _resultsStringFld, NSViewWidthSizable )
end fn
 
local fn Commands as CFArrayRef
CFStringRef cmd, string
long abbrLen
CFMutableArrayRef commands = fn MutableArrayWithCapacity(0)
ScannerRef scanner
string = @" add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3"
string = fn StringByAppendingString( string, @" compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate" )
string = fn StringByAppendingString( string, @" 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2" )
string = fn StringByAppendingString( string, @" forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load" )
string = fn StringByAppendingString( string, @" locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2" )
string = fn StringByAppendingString( string, @" msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3" )
string = fn StringByAppendingString( string, @" refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left" )
string = fn StringByAppendingString( string, @" 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1" )
scanner = fn ScannerWithString( string )
while ( fn ScannerIsAtEnd( scanner ) == NO )
if ( fn ScannerScanUpToCharactersFromSet( scanner, fn CharacterSetWhitespaceAndNewlineSet, @cmd ) )
abbrLen = 0
fn ScannerScanInteger( scanner, @abbrLen )
MutableArrayAddObject( commands, @{@"cmd":cmd,@"len":@(abbrLen)} )
end if
wend
end fn = commands
 
void local fn Validate
CFArrayRef commands, words
CFStringRef userString, result, wd, cmd
long wordCount, i, wordLen, abbrLen
CFMutableStringRef results
CFDictionaryRef dict
BOOL found
commands = fn Commands
userString = fn ControlStringValue( _userStringFld )
words = fn StringComponentsSeparatedByCharactersInSet( userString, fn CharacterSetWhitespaceAndNewlineSet )
results = fn MutableStringWithCapacity( 0 )
wordCount = len( words )
for i = 0 to wordCount - 1
found = NO
result = @"*error* "
wd = words[i]
wordLen = len( wd )
if ( wordLen )
for dict in commands
cmd = dict[@"cmd"]
abbrLen = fn NumberIntegerValue(dict[@"len"])
if ( abbrLen != 0 and wordLen >= abbrLen )
found = fn StringHasPrefix( lcase( cmd ), lcase( wd ) )
else
found = fn StringIsEqual( lcase( cmd ), lcase( wd ) )
end if
if ( found )
result = fn StringWithFormat( @"%@ ",ucase( cmd ) )
break
end if
next
MutableStringAppendString( results, result )
end if
next
ControlSetStringValue( _resultsStringFld, results )
end fn
 
 
void local fn DoDialog( ev as long, tag as long )
select ( ev )
case _btnClick : fn Validate
end select
end fn
 
 
editmenu 1
fn BuildWindow
 
on dialog fn DoDialog
 
HandleEvents</syntaxhighlight>
 
{{out}}
<pre>
user string: riG rePEAT copies put mo rest types fup. 6 poweRin
results string: RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
</pre>
 
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,756 ⟶ 2,330:
printResults(words, results)
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,766 ⟶ 2,340:
=={{header|Haskell}}==
{{Trans|Python}}
<langsyntaxhighlight lang="haskell">import Data.List (find, isPrefixOf)
import Data.Char (isDigit, toUpper)
import Data.Maybe (maybe)
Line 1,811 ⟶ 2,385:
unAbbrev
"riG rePEAT copies put mo rest types fup. 6 poweRin"
print $ unAbbrev ""</langsyntaxhighlight>
{{Out}}
<pre>"RIGHT REPEAT *error PUT MOVE RESTORE *error *error *error POWERINPUT"
Line 1,817 ⟶ 2,391:
 
=={{header|J}}==
<syntaxhighlight lang="j">ctable=:|:(({.;~{:@(_,".)@;@}.);.1~ _2<nc) cut {{)n
Warning: http://rosettacode.org/wiki/Abbreviations,_easy#J uses this code without duplication. Must provide expand with the same signature. x is the command table string, y is the user sentence.
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
<lang J>
range=:<.+[:i.>.-<.
assert 2 3 4 -: 2 range 5
assert (i.0) -: 3 range 3
 
abbreviate =: 3 :0
NB. input is the abbreviation table
NB. output are the valid abbreviations
y =. toupper CRLF -.~ y
y =. ;: y
y =. (([: (,3":#)L:_1 {)`[`]}~ ([: I. [: -. {.@e.&Num_j_&>)) y
y =. [&.:(;:inv) y
y =. _2 ({. , <./@:".&.>@:{:)\ y
y =. (<@] , ((range #) <@{."0 _ ]))&.>~/"1 y
ambiguities =. ;#~1<[:+/e.
(([: ~. {.@:[ , -.)L:_1 <@:ambiguities) y
)
assert ('ABC A AB' ,&(<@;:) 'ABCDE ABCD') -: abbreviate 'abc 1 abcde 3'
assert ('ABC A AB' ,&(<@;:) 'ABCDE') -: abbreviate 'abc 1 abcde'
 
 
expand =: dyad define
a =. abbreviate x
words =. <;._2 ' ' ,~ deb toupper y
interval_index =. <: +/\ #&> a
a =. a , <,<'*error*'
;:inv {.&> (interval_index I.(; a )i."_ 0 words){ a
)
</lang>
 
<pre>
command_table =: 0 :0
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
Line 1,858 ⟶ 2,400:
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
}} -.LF
)
findmatch=: {{
lens=. >{.ctable
for_ndx. I.y-:"1&tolower (#y){.&> list do. cmd=. ;(<1,ndx){ctable
if. (#y) >: ndx{lens do. toupper cmd return. end.
if. y -: cmd do. toupper cmd return. end.
end.
'*error*'
}}L:0</syntaxhighlight>
 
Task:
user_words =: 'riG rePEAT copies put mo rest types fup. 6 poweRin'
<syntaxhighlight lang="j"> ;:inv findmatch cut ' riG rePEAT copies put mo rest types fup. 6 poweRin'
 
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT</syntaxhighlight>
command_table expand user_words
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
</pre>
 
=={{header|Java}}==
{{Trans|C++}}
<langsyntaxhighlight lang="java">import java.util.*;
 
public class Abbreviations {
Line 1,959 ⟶ 2,508:
private List<Command> commands = new ArrayList<>();
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,970 ⟶ 2,519:
{{Trans|Haskell}}
{{Trans|Python}}
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 2,212 ⟶ 2,761:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>Abbreviation tests:
Line 2,220 ⟶ 2,769:
'' ->
''</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq, and with fq.'''
 
''' Adapted from [[#Wren|Wren]]
<syntaxhighlight lang=jq>
def table:
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " +
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " +
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " +
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " +
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " +
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " +
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " +
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"
;
 
# Input: {commands, minLens}
# Output: array of expansions or error markers corresponding to $words
def validate($words):
.commands as $commands
| .minLens as $minLens
| [ $words[] as $word
| ($word|length) as $wlen
| first( range(0; $commands|length) as $i
| $commands[$i]
| select($minLens[$i] != 0 and $wlen >= $minLens[$i] and $wlen <= length)
| ascii_upcase
| select(startswith(($word|ascii_upcase))) )
// "*error*" ];
 
 
# Output: {commands, minLens} corresponding to the $table string
def commands($table):
[$table|splits(" *")] as $split_table
| ($split_table|length) as $slen
| {commands:[], minLens:[], i:0}
| until(.found;
.commands += [ $split_table[.i] ]
| ($split_table[.i]|length) as $len
| if (.i == $slen - 1)
then .minLens += [$len]
| .found = true
else .
end
| .i += 1
| ($split_table[.i] | try (tonumber) // null) as $num
| if ($num != null)
then .minLens += [ if ($num < $len) then $num else $len end ]
| .i += 1
| if (.i == $slen) then .found = true else . end
else .minLens += [$len]
end );
 
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
 
def task($sentence):
[$sentence | splits(" *")] as $words
| commands(table)
| validate($words)
| $words, .
| map(lpad(10))
| join(" ") ;
 
task("riG rePEAT copies put mo rest types fup. 6 poweRin")
</syntaxhighlight>
{{output}}
'''Invocation''' jq -rnf abbreviations-simple.jq
</pre>
riG rePEAT copies put mo rest types fup. 6 poweRin
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
</pre>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">
const commandtable = """
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
Line 2,268 ⟶ 2,890:
 
teststring("riG rePEAT copies put mo rest types fup. 6 poweRin")
</langsyntaxhighlight> {{output}} <pre>
riG rePEAT copies put mo rest types fup. 6 poweRin
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
Line 2,274 ⟶ 2,896:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="kotlin">import java.util.Locale
 
private const val table = "" +
Line 2,327 ⟶ 2,949:
println("full words: ${results.joinToString(" ")}")
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,334 ⟶ 2,956:
full words: RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
</pre>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">abbr = {
define = function(self, cmdstr)
local cmd
self.hash = {}
for word in cmdstr:upper():gmatch("%S+") do
if cmd then
local n = tonumber(word)
for len = n or #cmd, #cmd do
self.hash[cmd:sub(1,len)] = cmd
end
cmd = n==nil and word or nil
else
cmd = word
end
end
end,
expand = function(self, input)
local output = {}
for word in input:upper():gmatch("%S+") do
table.insert(output, self.hash[word] or "*error*")
end
return table.concat(output, " ")
end
}
abbr:define[[
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
]]
local input = "riG rePEAT copies put mo rest types fup. 6 poweRin"
print("Input:", input)
print("Output:", abbr:expand(input))</syntaxhighlight>
{{out}}
<pre>Input: riG rePEAT copies put mo rest types fup. 6 poweRin
Output: RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT</pre>
 
=={{header|M2000 Interpreter}}==
===Using a List Object===
Object Queue is a list (using a hash table) which can hold same keys (strings or numbers or mix of them). Always the Exist(aQueuePointer, "word") set the internal index to the last key with name "word" if return true. We read the item in that index using Eval$(aQueuePointer) for string value, or Eval(aQueuePointer) for aritmetic value. We can't delete keys from anywhere, but only from the last entries using Drop statement to drop a number of keys. Here we didn't use drop, we have only a table of words.
 
<syntaxhighlight lang="m2000 interpreter">
Module Abbreviations_Simple {
Function Lex {
a$={add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
}
const crlftab$={
}+chr$(9)
Lex=Queue
Word$=""
dim part$()
part$()=piece$(trim$(filter$(a$, crlftab$)), " ")
for i=0 to len(part$())-1
if part$(i)<>"" then
k=val(part$(i))
if k=0 then
if Word$<>"" then Append Lex, Word$:=Word$
Word$=ucase$(part$(i))
else
for j=k to len(Word$)
Append Lex, left$(Word$,j):=Word$
next j
word$=""
end if
end if
next i
if Word$<>"" then Append Lex, Word$:=Word$
=Lex
}
Parse$=Lambda$ Lex=Lex() (a$) -> {
Dim part$()
Rep$=""
part$()=piece$(a$," ")
if len(part$())=0 then exit
for i=0 to len(part$())-1
if part$(i)<>"" then
if exist(Lex, ucase$(part$(i))) then
Rep$+=if$(Rep$=""->"", " ")+Eval$(lex)
else
Rep$+=if$(Rep$=""->"", " ")+"*error*"
end if
end if
next i
=Rep$
}
Print Parse$("riG rePEAT copies put mo rest types fup. 6 poweRin")
Print Parse$("riG macro copies macr")
Print Parse$("")=""
}
Abbreviations_Simple
</syntaxhighlight>
{{out}}
<pre>
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
RIGHT MACRO *error* *error*
True
</pre>
===Using simple string===
Here we use just a string to hold the words and the Instr() function to search for each abbreviation.
 
<syntaxhighlight lang="m2000 interpreter">
Module Abbreviations_Simple_2 {
Function Lex$ {
a$={add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
}
const crlftab$={
}+chr$(9)
Lex$=""
Word$=""
dim part$()
part$()=piece$(trim$(filter$(a$, crlftab$)), " ")
for i=0 to len(part$())-1
if part$(i)<>"" then
k=val(part$(i))
if k=0 then
if Word$<>"" then Lex$+="#"+Word$+" 0"
Word$=ucase$(part$(i))
else
Lex$+="#"+ Word$+str$(k)
word$=""
end if
end if
next i
if Word$<>"" then Lex$+="#"+Word$+" 0"
=Lex$
}
Parse$=Lambda$ Lex$=Lex$() (a$) -> {
Dim part$()
Rep$=""
part$()=piece$(a$," ")
if len(part$())=0 then exit
for i=0 to len(part$())-1
if part$(i)<>"" then
j=1
do
j=instr(Lex$, "#"+ucase$(part$(i)), j)
if j=0 then exit
q=instr(Lex$, " ", j+1)
if Val(Mid$(lex$, q,10))=0 then
if Mid$(Lex$, j+1, q-j)=ucase$(part$(i))+" " then exit
else.if len(part$(i))>=Val(Mid$(lex$, q,10)) then
exit
end if
j++
Always
if j>0 then
Rep$+=if$(Rep$=""->"", " ")+Mid$(Lex$, j+1, q-j-1)
else
Rep$+=if$(Rep$=""->"", " ")+"*error*"
end if
end if
next i
=Rep$
}
Print Parse$("riG rePEAT copies put mo rest types fup. 6 poweRin")
Print Parse$("riG macro copies macr")
Print Parse$("")=""
}
Abbreviations_Simple_2
</syntaxhighlight>
{{out}}
<pre>
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
RIGHT MACRO *error* *error*
True
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ClearAll[ct, FunctionMatchQ, ValidFunctionQ, ProcessString]
ct = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1";
ct = FixedPoint[StringReplace[{"\n" -> "", Longest[" " ..] -> " "}], ct];
ct = StringSplit[ct, " "];
ct = SequenceReplace[ct, {x_, y : (Alternatives @@ (ToString /@ Range[1, 9]))} :> {x, ToExpression@y}];
ct = If[MatchQ[#, {_, _Integer}], #, {#, 1}] & /@ ct;
FunctionMatchQ[{func_String, min_Integer}, test_String] :=
Module[{max, l},
max = StringLength[func];
l = StringLength[test];
If[min <= l <= max,
If[StringStartsQ[func, test, IgnoreCase -> True],
True
,
False
]
,
False
]
]
ValidFunctionQ[test_String] := Module[{val},
val = SelectFirst[ct, FunctionMatchQ[#, test] &, Missing[]];
If[MissingQ[val], "*error*", ToUpperCase[First@val]]
]
ProcessString[test_String] := Module[{parts},
parts = StringSplit[test];
StringRiffle[ValidFunctionQ /@ parts, " "]
]
ProcessString["riG rePEAT copies put mo rest types fup. 6 poweRin"]</syntaxhighlight>
{{out}}
<pre>"RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT"</pre>
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">c = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3" +
" compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate" +
" 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2" +
Line 2,377 ⟶ 3,227:
output.push check(word)
end for
print output.join</langsyntaxhighlight>
 
{{out}}
<pre>RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT</pre>
 
 
=={{header|Nim}}==
{{Trans|Python}}
Adapted from Python version with several modifications.
<syntaxhighlight lang="nim">
<lang Nim>
import parseutils
import strutils
Line 2,462 ⟶ 3,311:
echo ""
break
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,474 ⟶ 3,323:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">open String
 
let table_as_string =
Line 2,488 ⟶ 3,337:
replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left 2 \
save set shift 2 si sort sos stack 3 status 4 top \
transfer 3 type 1 up 1"</langsyntaxhighlight>
 
The interesting part below is the '''compare''' function.
Line 2,496 ⟶ 3,345:
but for the latter, we need to ensure that the word corresponds to the abbreviation
(the abbreviation is a substring of the word and the abbreviation length is sufficient).
<langsyntaxhighlight lang="ocaml">module Entry = struct
type t = { word : string ; min : int }
let compare e1 e2 =
Line 2,506 ⟶ 3,355:
end
 
module Table = Set.Make(Entry)</langsyntaxhighlight>
 
The few functions below are used to build the table from the string at the beginning.
<langsyntaxhighlight lang="ocaml">let clean_strings strs =
List.filter (fun w -> w <> "" && w <> " ") strs
 
Line 2,529 ⟶ 3,378:
split_on_char ' ' table_as_string
|> clean_strings
|> split</langsyntaxhighlight>
 
Finally, here is the function looking for a word :
<langsyntaxhighlight lang="ocaml">let abbrev (table:Table.t) (w:string) : string =
let w = uppercase_ascii w in
try
Line 2,547 ⟶ 3,396:
let inputs = ["riG";"rePEAT";"copies";"put";"mo";"rest";"types";"fup.";"6";"poweRin"] in
check table inputs;
exit 0</langsyntaxhighlight>
 
{{out}}
Line 2,555 ⟶ 3,404:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">@c = (uc join ' ', qw<
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
Line 2,583 ⟶ 3,432:
}
 
print "$inp\n$out\n";</langsyntaxhighlight>
{{out}}
<pre>Input: riG rePEAT copies put mo rest types fup. 6 poweRin
Line 2,590 ⟶ 3,439:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">-->
<lang Phix>constant abbrtxt = """
<span style="color: #008080;">constant</span> <span style="color: #000000;">abbrtxt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4add copy1 2 countalter 3 Coverlay 3backup cursor2 3 bottom delete1 3 CdeleteCappend 2 downchange 1 duplicateSchange Cinsert 2 Clast 3
3 xEditcompress 14 expandcopy 32 extractcount 3 Coverlay find3 1cursor Nfind3 2 Nfindup 6 NfUPdelete 3 CfindCdelete 2 findUP 3down fUP1 2 duplicate
forward 23 xEdit get1 expand help3 1extract hexType3 4 inputfind 1 powerInputNfind 32 Nfindup join6 1NfUP split3 Cfind 2 spltJOINfindUP load3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg nextlocate 1 overlayClocate 12 parselowerCase preserve3 4 purgeupperCase 3 putLprefix putD2 query 1macro quit merge read2 recovermodify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
""",
"""</span><span style="color: #0000FF;">,</span>
input = "riG rePEAT copies put mo rest types fup. 6 poweRin"
<span style="color: #000000;">input</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"riG rePEAT copies put mo rest types fup. 6 poweRin"</span>
 
function set_min_lengths(sequence a)
<span style="color: #008080;">function</span> <span style="color: #000000;">set_min_lengths</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
--
<span style="color: #000080;font-style:italic;">--
-- set default lengths and apply min lengths if present, eg ..."macro","merge","2",...
-- set ==>default {.."macro"lengths and apply min lengths if present,5}} ==>eg {..."macro",5},{"merge",5}} ==> {.."macro2",5},{"merge",2}}...
-- ==&gt; {.."macro",5}} ==&gt; {.."macro",5},{"merge",5}} ==&gt; {.."macro",5},{"merge",2}}
-- ie both macro and merge get a default min length of 5, but the min length of merge
-- ie both macro and merge get a default min length of 5, but the min length of merge
-- is overwritten when the "2" is processed.
-- is overwritten when the "2" is processed.
--
--</span>
sequence res = {}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
for i=1 to length(a) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
string ai = a[i]
<span style="color: #004080;">string</span> <span style="color: #000000;">ai</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
if length(ai)=1 and ai>="1" and ai<="9" then
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ai</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">1</span> <span style="color: #008080;">and</span> <span style="color: #000000;">ai</span><span style="color: #0000FF;">>=</span><span style="color: #008000;">"1"</span> <span style="color: #008080;">and</span> <span style="color: #000000;">ai</span><span style="color: #0000FF;"><=</span><span style="color: #008000;">"9"</span> <span style="color: #008080;">then</span>
res[$][2] = ai[1]-'0'
<span style="color: #000000;">res</span><span style="color: #0000FF;">[$][</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ai</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]-</span><span style="color: #008000;">'0'</span>
else
<span res style="color: append(res,{ai,length(ai)})#008080;">else</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">ai</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ai</span><span style="color: #0000FF;">)})</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return res
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
constant abbrevs = set_min_lengths(split(substitute(abbrtxt,"\n"," "),no_empty:=true))
<span style="color: #008080;">constant</span> <span style="color: #000000;">abbrevs</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">set_min_lengths</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">substitute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">abbrtxt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">),</span><span style="color: #000000;">no_empty</span><span style="color: #0000FF;">:=</span><span style="color: #004600;">true</span><span style="color: #0000FF;">))</span>
constant inputs = split(input,no_empty:=true)
<span style="color: #008080;">constant</span> <span style="color: #000000;">inputs</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #000000;">input</span><span style="color: #0000FF;">,</span><span style="color: #000000;">no_empty</span><span style="color: #0000FF;">:=</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
 
for i=1 to length(inputs) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">inputs</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
string ii = inputs[i],
<span style="color: #004080;">string</span> <span style="color: #000000;">ii</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">inputs</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span>
res = "*error*"
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"*error*"</span>
for j=1 to length(abbrevs) do
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">abbrevs</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
{string aj, integer l} = abbrevs[j]
<span style="color: #0000FF;">{</span><span style="color: #004080;">string</span> <span style="color: #000000;">aj</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">l</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">abbrevs</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span>
if length(ii)>=l
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ii</span><span style="color: #0000FF;">)>=</span><span style="color: #000000;">l</span>
and match(ii,aj,case_insensitive:=true)==1 then
<span style="color: #008080;">and</span> <span style="color: #7060A8;">match</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ii</span><span style="color: #0000FF;">,</span><span style="color: #000000;">aj</span><span style="color: #0000FF;">,</span><span style="color: #000000;">case_insensitive</span><span style="color: #0000FF;">:=</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)==</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
res = upper(aj)
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">upper</span><span style="color: #0000FF;">(</span><span style="color: #000000;">aj</span><span style="color: #0000FF;">)</span>
exit
<span style="color: #008080;">exit</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
puts(1,res&" ")
<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: #000000;">res</span><span style="color: #0000FF;">&</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
puts(1,"\n")</lang>
<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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,646 ⟶ 3,497:
====Procedural====
{{works with|Python|3.6}}
<langsyntaxhighlight lang="python">
 
command_table_text = """add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
Line 2,708 ⟶ 3,559:
print("user words:", user_words)
print("full words:", full_words)
</syntaxhighlight>
</lang>
{{out}}
<pre>input: ""
Line 2,719 ⟶ 3,570:
====Composition of pure functions====
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Simple abbreviations'''
 
from functools import reduce
Line 2,889 ⟶ 3,740:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Simple abbreviations:
Line 2,899 ⟶ 3,750:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
(require srfi/13)
 
Line 2,940 ⟶ 3,791:
(validate-string "riG rePEAT copies put mo rest types fup. 6 poweRin")
"RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT")
(check-equal? (validate-string "") ""))</langsyntaxhighlight>
{{out}}
<pre>input: ""
Line 2,954 ⟶ 3,805:
Demonstrate that inputting an empty string returns an empty string in addition to the required test input.
 
<syntaxhighlight lang="raku" perl6line><
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
Line 2,977 ⟶ 3,828:
put ' Input: ', $str;
put 'Output: ', join ' ', $str.words.map: &abbr-simple;
}</langsyntaxhighlight>
{{out}}
<pre> Input: riG rePEAT copies put mo rest types fup. 6 poweRin
Line 2,985 ⟶ 3,836:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program validates a user "word" against a "command table" with abbreviations.*/
parseParse argArg uw /*obtain optional arguments from the CL*/
ifIf uw='' thenThen uw= 'riG rePEAT copies put mo rest types fup. 6 poweRin'
saySay 'user words: ' uw
 
@keyws= 'add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3',
'compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate',
'3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2',
'forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load',
'locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2',
'msg next 1 overlay 1 parseParse preserve 4 purge 3 put putD query 1 quit read recover 3',
'refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left',
'2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1'
 
saySay 'full words: ' validate(uw) /*display the result(s) to the terminal*/
exitExit /*stick a fork in it, we're all done. */
/*--------------------------------------------------------------------------------------*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
validate: Procedure Expose keyws
validate: procedure expose @; arg x; upper @ /*ARG capitalizes all the X words. */
keyws=translate(keyws)
$= /*initialize the return string to null.*/
Arg userwords do j=1 to words(x); _=word(x, j) /*obtain a word from the X list./*ARG capitalizes all the userwords. */
res='' do k=1 to words(@); a=word(@, k) /*get a legitmate command name from @ /*initialize the Return string to null.*/
Do j=1 to words(userwords) L=word(@, k+1) /* loop over userwords /*··· and maybe get it's abbrev length.*/
uword=word(userwords,j) if datatype(L, 'W') then k=k + 1/*obtain a word from the userword /*yuppers, it's an abbrev lengthlist.*/
Do k=1 to words(keyws) /* loop over keywords else L=length(a) /*nope, it can't be abbreviated.*/
kw=word(keyws,k) if abbrev(a, _, L) then do; $=$ a; iterate/*get j;a legitmate endcommand name /*is validfrom abbrev?keyws.*/
L=word(keyws,k+1) end /*k··· and maybe get its abbrev length.*/
If $=$ datatype(L,'*error*W') Then /* it's a number - /*processedan theabbrev wholelength. list, not valid. */
k=k + 1 end /*j skip it for next kw */
Else return strip($) /*elide theotherwise superfluous leading blank. */</lang>
L=length(kw) /* it can't be abbreviated. */
If abbrev(kw,uword,L) Then Do /* is valid abbreviation */
res=res kw /* add to result string */
Iterate j /* proceed with next userword */
End
End
res=res '*error*' /*processed the whole list, not valid */
End
Return strip(res) /* elide superfluous leading blank. */
</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 3,021 ⟶ 3,882:
 
=={{header|Ruby}}==
<langsyntaxhighlight Rubylang="ruby">str = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
Line 3,043 ⟶ 3,904:
 
puts ar.join(" ")
</syntaxhighlight>
</lang>
{{out}}
<pre>RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
Line 3,051 ⟶ 3,912:
{{works with|Rust|1.35.0}}
cargo clippy and cargo fmt run against it
<langsyntaxhighlight lang="rust">use std::collections::HashMap;
 
// The plan here is to build a hashmap of all the commands keyed on the minimum number of
Line 3,161 ⟶ 4,022:
let correct_output = "RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT";
assert_eq!(output_text, correct_output)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,169 ⟶ 4,030:
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">
<lang Scala>
object Main extends App {
implicit class StrOps(i: String) {
Line 3,215 ⟶ 4,076:
println(resultLine)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
</pre>
 
=={{header|SNOBOL4}}==
{{works with|SNOBOL4, SPITBOL for Linux}}
<syntaxhighlight lang="snobol4">
* Program: abbr_simple.sbl
* To run: sbl abbr_simple.sbl
* Description: Abbreviations, simple
* Comment: Tested using the Spitbol for Linux version of SNOBOL4
 
commands =
+ "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 "
+ "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate "
+ "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
+ "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load "
+ "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 "
+ "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 "
+ "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
+ "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 "
 
commands = replace(commands,&lcase,&ucase)
numerals = '0123456789'
 
 
* Function filltable will fill the command abbreviations table
define("filltable(s,n)slen,i")
ct = table(300, ,"*error*") :f(errr);* command abbreviations table
:(filltable_end)
filltable
slen = size(s)
ct[s] = s
eq(n,slen) :s(filltable3)
i = n - 1
filltable2
i = lt(i,slen - 1) i + 1 :f(filltable3)
ct[substr(s,1,i)] = s
:(filltable2)
filltable3
filltable = ""
:(return)
filltable_end
 
 
x0
* Populate command abbreviations table
commands ? (span(' ') | "") breakx(&ucase) span(&ucase) . c
+ span(' ') (span(numerals) | "") . ablen = "" :f(x1)
ablen = ident(ablen) size(c)
ret = filltable(c,ablen)
:(x0)
x1
* Process user string
userstring = "riG rePEAT copies put mo rest types fup. 6 poweRin"
output = "Original user string:"
output = userstring
userstring = replace(userstring,&lcase,&ucase)
x2
userstring ? (span(' ') | "") (break(' ') | (len(1) rem)) . c = "" :f(x3)
user_commands = (gt(size(user_commands),0) user_commands ' ' ct[c], ct[c])
:(x2)
x3
output = ""
output = "User string with abbreviations expanded:"
output = user_commands
 
END
</syntaxhighlight>
{{out}}
<pre>
Original user string:
riG rePEAT copies put mo rest types fup. 6 poweRin
 
User string with abbreviations expanded:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
</pre>
Line 3,223 ⟶ 4,158:
=={{header|Tcl}}==
 
<langsyntaxhighlight lang="tcl">proc appendCmd {word} {
# Procedure to append the correct command from the global list ::cmds
# for the word given as parameter to the global list ::result.
Line 3,261 ⟶ 4,196:
 
puts "user words: $words"
puts $result</langsyntaxhighlight>
{{out}}<pre>./abbreviations_simple.tcl
user words: riG rePEAT copies put mo rest types fup. 6 poweRin
Line 3,268 ⟶ 4,203:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Private Function ValidateUserWords(userstring As String) As String
Dim s As String
Dim user_words() As String
Line 3,326 ⟶ 4,261:
Debug.Print "full words:", ValidateUserWords(guserstring)
End Sub
</syntaxhighlight>
</lang>
{{out}}<pre>user words: riG rePEAT copies put mo rest types fup. 6 poweRin
full words: RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
</pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
option explicit
 
function iif(c,t,f) if c then iif=t else iif=f end if: end function
function usrin(pr) wscript.stdout.write vbcrlf &pr &": ":usrin= wscript.stdin.readline:end function
 
sub do_abbrev
dim j, sm,n,n0,a
for each j in m
sm=trim(lcase(j.submatches(0)))
n0=iif (j.submatches(1)="",1, j.submatches(1))
n=1
do
a=left(sm,n)
if not d.exists(a) then
d.add a,sm
else
if len(a)=len(sm) then
d(a)=sm
elseif len(d(a))>len(a) then
d(a)=null
end if
end if
n=n+1
loop until n>len(sm)
next
end sub
'output sorted
 
sub display
dim d2,k,j,kk,mm
set d2=createobject("Scripting.dictionary")
for each k in d
kk=d(k)
if not isnull(kk) then
if not d2.exists(kk) then
d2.add kk,k
else
d2(kk)= d2(kk) & " " & k
end if
end if
next
for each j in m
mm=trim(lcase(j.submatches(0)))
wscript.echo left(mm&space(15),15),d2(mm)
next
wscript.echo
set d2=nothing
end sub
 
sub test
wscript.echo vbcrlf&"test:"
dim a,i,k,s1
do
s1= lcase(usrin("Command?"))
if trim(s1)="" then wscript.quit
a=split(trim(s1)," ")
for i=0 to ubound(a)
if a(i)<>"" then
wscript.stdout.write iif (d.exists(a(i)), ucase(d(a(i)))," **ERROR**")& " "
end if
next
loop
end sub
 
'main program
dim s:s=_
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 "&_
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate "&_
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "&_
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load "&_
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 "&_
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 "&_
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "&_
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 "
dim m,d
 
'use regexp to separate input
with new regexp
.pattern="([a-z]+?)\s+(\d?)"
.global=true
.ignorecase=true
set m=.execute(s)
end with
 
set d=createobject("Scripting.dictionary")
do_abbrev
'display
test
</syntaxhighlight>
{{out}}
<pre>
Command?: riG rePEAT copies put mo rest types fup. 6 poweRin
RIGHT REPEAT **ERROR** PUT RESTORE **ERROR** **ERROR** **ERROR** POWERINPUT
</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">import encoding.utf8
import strconv
fn read_table(table string) ([]string, []int) {
fields := table.fields()
mut commands := []string{}
mut min_lens := []int{}
for i, max := 0, fields.len; i < max; {
cmd := fields[i]
mut cmd_len := cmd.len
i++
if i < max {
num := strconv.atoi(fields[i]) or {-1}
if 1 <= num && num < cmd_len {
cmd_len = num
i++
}
}
commands << cmd
min_lens << cmd_len
}
return commands, min_lens
}
fn validate_commands(commands []string, min_lens []int, words []string) []string {
mut results := []string{}
for word in words {
mut match_found := false
wlen := word.len
for i, command in commands {
if min_lens[i] == 0 || wlen < min_lens[i] || wlen > command.len {
continue
}
c := utf8.to_upper(command)
w := utf8.to_upper(word)
if c.index(w) or {-1} == 0 {
results << c
match_found = true
break
}
}
if !match_found {
results << "*error*"
}
}
return results
}
fn print_results(words []string, results []string) {
println("user words:\t${words.join("\t")}")
println("full words:\t${results.join("\t")}")
}
fn main() {
table := "" +
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " +
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " +
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " +
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " +
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " +
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " +
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " +
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 "
sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin"
commands, min_lens := read_table(table)
words := sentence.fields()
results := validate_commands(commands, min_lens, words)
print_results(words, results)
}
</syntaxhighlight>
 
{{out}}
<pre>
user words: riG rePEAT copies put mo rest types fup. 6 poweRin
full words: RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
</pre>
 
Line 3,335 ⟶ 4,452:
{{libheader|Wren-str}}
Based on an older version of the Go entry.
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
import "./str" for Str
 
var table =
Line 3,403 ⟶ 4,520:
}
System.write("\nfull words: ")
System.print(results.join(" "))</langsyntaxhighlight>
 
{{out}}
Line 3,412 ⟶ 4,529:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">c$ = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3"
c$ = c$ + " compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate"
c$ = c$ + " 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2"
Line 3,460 ⟶ 4,577:
next
 
print r$</langsyntaxhighlight>
 
{{out}}
Line 3,468 ⟶ 4,585:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">commands:=Data(0,String, // "add\01\0alter\0..."
#<<<
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
Line 3,501 ⟶ 4,618:
n+=c.len();
}
}).concat(" ").println();</langsyntaxhighlight>
{{out}}
<pre>
2,289

edits