Range expansion: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 17: Line 17:
=={{header|11l}}==
=={{header|11l}}==
{{trans|Python}}
{{trans|Python}}
<lang 11l>F rangeexpand(txt)
<syntaxhighlight lang="11l">F rangeexpand(txt)
[Int] lst
[Int] lst
L(r) txt.split(‘,’)
L(r) txt.split(‘,’)
Line 27: Line 27:
R lst
R lst


print(rangeexpand(‘-6,-3--1,3-5,7-11,14,15,17-20’))</lang>
print(rangeexpand(‘-6,-3--1,3-5,7-11,14,15,17-20’))</syntaxhighlight>


=={{header|8th}}==
=={{header|8th}}==
<lang Forth>\ Given a low and high limit, create an array containing the numbers in the
<syntaxhighlight lang="forth">\ Given a low and high limit, create an array containing the numbers in the
\ range, inclusive:
\ range, inclusive:
: n:gen-range \ low hi -- a
: n:gen-range \ low hi -- a
Line 90: Line 90:
n:range-expand
n:range-expand
\ print the expanded list:
\ print the expanded list:
. cr bye</lang>
. cr bye</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 97: Line 97:


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>BYTE FUNC Find(CHAR ARRAY text CHAR c BYTE start)
<syntaxhighlight lang="action!">BYTE FUNC Find(CHAR ARRAY text CHAR c BYTE start)
BYTE i
BYTE i


Line 168: Line 168:
RangeExtraction("-6,-3--1,3-5,7-11,14,15,17-20",res,@size)
RangeExtraction("-6,-3--1,3-5,7-11,14,15,17-20",res,@size)
PrintArray(res,size)
PrintArray(res,size)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Range_expansion.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Range_expansion.png Screenshot from Atari 8-bit computer]
Line 178: Line 178:
The function Expand takes a string and returns a corresponding array of integers.
The function Expand takes a string and returns a corresponding array of integers.
Upon syntax errors Constraint_Error is propagated:
Upon syntax errors Constraint_Error is propagated:
<lang Ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Range_Expansion is
procedure Test_Range_Expansion is
type Sequence is array (Positive range <>) of Integer;
type Sequence is array (Positive range <>) of Integer;
Line 243: Line 243:
begin
begin
Put (Expand ("-6,-3--1,3-5,7-11,14,15,17-20"));
Put (Expand ("-6,-3--1,3-5,7-11,14,15,17-20"));
end Test_Range_Expansion;</lang>
end Test_Range_Expansion;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 251: Line 251:
=={{header|Aime}}==
=={{header|Aime}}==
{{incorrect|Aime|Needs "a comma separated list" without the trailing comma}}
{{incorrect|Aime|Needs "a comma separated list" without the trailing comma}}
<lang aime>list l;
<syntaxhighlight lang="aime">list l;


file().b_affix("-6,-3--1,3-5,7-11,14,15,17-20").news(l, 0, 0, ",");
file().b_affix("-6,-3--1,3-5,7-11,14,15,17-20").news(l, 0, 0, ",");
Line 270: Line 270:
}
}


o_("\n");</lang>
o_("\n");</syntaxhighlight>
or:
or:
<lang aime>integer p;
<syntaxhighlight lang="aime">integer p;
list l;
list l;


Line 285: Line 285:
}
}


o_("\n");</lang>
o_("\n");</syntaxhighlight>
{{out}}
{{out}}
<pre>-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20,</pre>
<pre>-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20,</pre>
Line 293: Line 293:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny] - string parsing and formatting code tested with 2.6.win32}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny] - string parsing and formatting code tested with 2.6.win32}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<lang algol68>MODE YIELDINT = PROC(INT)VOID;
<syntaxhighlight lang="algol68">MODE YIELDINT = PROC(INT)VOID;


MODE RANGE = STRUCT(INT lwb, upb);
MODE RANGE = STRUCT(INT lwb, upb);
Line 462: Line 462:
print( ( TOSTRING range expand( TORANGE "-6,-3--1,3-5,7-11,14,15,17-20" ), newline ) )
print( ( TOSTRING range expand( TORANGE "-6,-3--1,3-5,7-11,14,15,17-20" ), newline ) )
)
)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 470: Line 470:
=={{header|APL}}==
=={{header|APL}}==
{{works with|Dyalog APL}}
{{works with|Dyalog APL}}
<lang APL>range←{
<syntaxhighlight lang="apl">range←{
aplnum←{⍎('¯',⎕D)[('-',⎕D)⍳⍵]}
aplnum←{⍎('¯',⎕D)[('-',⎕D)⍳⍵]}
∊{ 0::('Invalid range: ''',⍵,'''')⎕SIGNAL 11
∊{ 0::('Invalid range: ''',⍵,'''')⎕SIGNAL 11
Line 478: Line 478:
(s+(⍳e-s-1))-1
(s+(⍳e-s-1))-1
}¨(⍵≠',')⊆⍵
}¨(⍵≠',')⊆⍵
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 496: Line 496:
===Functional===
===Functional===
{{Trans|JavaScript}} (Functional ES5 version)
{{Trans|JavaScript}} (Functional ES5 version)
<lang AppleScript>-- Each comma-delimited string is mapped to a list of integers,
<syntaxhighlight lang="applescript">-- Each comma-delimited string is mapped to a list of integers,
-- and these integer lists are concatenated together into a single list
-- and these integer lists are concatenated together into a single list


Line 651: Line 651:
item 1 of tuple
item 1 of tuple
end if
end if
end tupleRange</lang>
end tupleRange</syntaxhighlight>
{{Out}}
{{Out}}
<lang AppleScript>{-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20}</lang>
<syntaxhighlight lang="applescript">{-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20}</syntaxhighlight>
----
----


===Idiomatic===
===Idiomatic===


<lang applescript>on rangeExpansion(rangeExpression)
<syntaxhighlight lang="applescript">on rangeExpansion(rangeExpression)
-- Split the expression at the commas, if any.
-- Split the expression at the commas, if any.
set astid to AppleScript's text item delimiters
set astid to AppleScript's text item delimiters
Line 688: Line 688:
-- Demo code:
-- Demo code:
set rangeExpression to "-6,-3--1,3-5,7-11,14,15,17-20"
set rangeExpression to "-6,-3--1,3-5,7-11,14,15,17-20"
return rangeExpansion(rangeExpression)</lang>
return rangeExpansion(rangeExpression)</syntaxhighlight>


{{output}}
{{output}}
<lang applescript>{-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20}</lang>
<syntaxhighlight lang="applescript">{-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20}</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>expandRange: function [rng][
<syntaxhighlight lang="rebol">expandRange: function [rng][
flatten @ to :block
flatten @ to :block
join.with:" " map split.by:"," rng 'x ->
join.with:" " map split.by:"," rng 'x ->
Line 703: Line 703:
]
]


print expandRange {-6,-3--1,3-5,7-11,14,15,17-20}</lang>
print expandRange {-6,-3--1,3-5,7-11,14,15,17-20}</syntaxhighlight>


{{out}}
{{out}}
Line 710: Line 710:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>msgbox % expand("-6,-3--1,3-5,7-11,14,15,17-20")
<syntaxhighlight lang="autohotkey">msgbox % expand("-6,-3--1,3-5,7-11,14,15,17-20")


expand( range ) {
expand( range ) {
Line 718: Line 718:
ret .= "," (A_Index-1) + f1
ret .= "," (A_Index-1) + f1
return SubStr(ret, 2)
return SubStr(ret, 2)
}</lang>
}</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==


<lang awk>#!/usr/bin/awk -f
<syntaxhighlight lang="awk">#!/usr/bin/awk -f
BEGIN { FS=","; }
BEGIN { FS=","; }


Line 743: Line 743:
}
}
return;
return;
} </lang>
} </syntaxhighlight>


<pre>
<pre>
Line 752: Line 752:


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> PRINT FNrangeexpand("-6,-3--1,3-5,7-11,14,15,17-20")
<syntaxhighlight lang="bbcbasic"> PRINT FNrangeexpand("-6,-3--1,3-5,7-11,14,15,17-20")
END
END
Line 774: Line 774:
ENDIF
ENDIF
UNTIL i% = 0
UNTIL i% = 0
= r$</lang>
= r$</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 781: Line 781:


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat> ( expandRanges
<syntaxhighlight lang="bracmat"> ( expandRanges
= a b L
= a b L
. @( !arg
. @( !arg
Line 796: Line 796:
)
)
& out$(str$(expandRanges$"-6,-3--1,3-5,7-11,14,15,17-20"))
& out$(str$(expandRanges$"-6,-3--1,3-5,7-11,14,15,17-20"))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20</pre>
<pre>-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20</pre>
Line 802: Line 802:
=={{header|C}}==
=={{header|C}}==
Recursive descent parser.
Recursive descent parser.
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <ctype.h>
#include <ctype.h>
Line 879: Line 879:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20
<pre>-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20
Line 888: Line 888:
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
{{works with|C sharp|3.0}}
{{works with|C sharp|3.0}}
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 917: Line 917:
Console.WriteLine(string.Join(", ", values));
Console.WriteLine(string.Join(", ", values));
}
}
}</lang>
}</syntaxhighlight>


{{works with|C sharp|3.5+}}
{{works with|C sharp|3.5+}}
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 950: Line 950:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <sstream>
#include <sstream>
#include <iterator>
#include <iterator>
Line 1,026: Line 1,026:
else
else
std::cout << "an error occured.";
std::cout << "an error occured.";
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20
-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20
Line 1,032: Line 1,032:
=={{header|Clojure}}==
=={{header|Clojure}}==
There is a split method in clojure.contrib, but I don't know if it is able to skip first character to so that <code>(split "-8--8") => (-8 -8)</code>.
There is a split method in clojure.contrib, but I don't know if it is able to skip first character to so that <code>(split "-8--8") => (-8 -8)</code>.
<lang clojure>(defn split [s sep]
<syntaxhighlight lang="clojure">(defn split [s sep]
(defn skipFirst [[x & xs :as s]]
(defn skipFirst [[x & xs :as s]]
(cond (empty? s) [nil nil]
(cond (empty? s) [nil nil]
Line 1,055: Line 1,055:


> (rangeexpand "-6,-3--1,3-5,7-11,14,15,17-20")
> (rangeexpand "-6,-3--1,3-5,7-11,14,15,17-20")
(-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20)</lang>
(-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20)</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
{{works with|GNU Cobol|2.0}}
{{works with|GNU Cobol|2.0}}
<lang cobol> >>SOURCE FREE
<syntaxhighlight lang="cobol"> >>SOURCE FREE
IDENTIFICATION DIVISION.
IDENTIFICATION DIVISION.
PROGRAM-ID. expand-range.
PROGRAM-ID. expand-range.
Line 1,151: Line 1,151:
END-IF
END-IF
.
.
END PROGRAM display-edited-num.</lang>
END PROGRAM display-edited-num.</syntaxhighlight>


Setup:
Setup:
Line 1,165: Line 1,165:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun expand-ranges (string)
<syntaxhighlight lang="lisp">(defun expand-ranges (string)
(loop
(loop
with prevnum = nil
with prevnum = nil
Line 1,187: Line 1,187:


CL-USER> (expand-ranges "-6,-3--1,3-5,7-11,14,15,17-20")
CL-USER> (expand-ranges "-6,-3--1,3-5,7-11,14,15,17-20")
(-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20)</lang>
(-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20)</syntaxhighlight>


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


# Callback interface
# Callback interface
Line 1,283: Line 1,283:
# Try it on a couple of wrong ones
# Try it on a couple of wrong ones
PrintExpansion("-6-3--1,3-5,7-11,14,15,17-20"); # misformatted range
PrintExpansion("-6-3--1,3-5,7-11,14,15,17-20"); # misformatted range
PrintExpansion("-6,-3--1,5-3,7-11,14,15,17-20"); # numbers not in order</lang>
PrintExpansion("-6,-3--1,5-3,7-11,14,15,17-20"); # numbers not in order</syntaxhighlight>


{{out}}
{{out}}
Line 1,296: Line 1,296:
=={{header|Crystal}}==
=={{header|Crystal}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang crystal>def range_expand(range)
<syntaxhighlight lang="crystal">def range_expand(range)
range.split(',').flat_map do |part|
range.split(',').flat_map do |part|
match = /^(-?\d+)-(-?\d+)$/.match(part)
match = /^(-?\d+)-(-?\d+)$/.match(part)
Line 1,307: Line 1,307:
end
end


puts range_expand("-6,-3--1,3-5,7-11,14,15,17-20")</lang>
puts range_expand("-6,-3--1,3-5,7-11,14,15,17-20")</syntaxhighlight>
{{out}}
{{out}}
<pre>[-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]</pre>
<pre>[-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]</pre>


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.regex, std.conv, std.range, std.algorithm;
<syntaxhighlight lang="d">import std.stdio, std.regex, std.conv, std.range, std.algorithm;


enum rangeEx = (string s) /*pure*/ => s.matchAll(`(-?\d+)-?(-?\d+)?,?`)
enum rangeEx = (string s) /*pure*/ => s.matchAll(`(-?\d+)-?(-?\d+)?,?`)
Line 1,319: Line 1,319:
void main() {
void main() {
"-6,-3--1,3-5,7-11,14,15,17-20".rangeEx.writeln;
"-6,-3--1,3-5,7-11,14,15,17-20".rangeEx.writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]</pre>
<pre>[-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]</pre>
Line 1,325: Line 1,325:
{{libheader| System.SysUtils}}
{{libheader| System.SysUtils}}
{{Trans|Go}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Range_expansion;
program Range_expansion;


Line 1,395: Line 1,395:
end;
end;
readln;
readln;
end.</lang>
end.</syntaxhighlight>




=={{header|DWScript}}==
=={{header|DWScript}}==
<lang pascal>
<syntaxhighlight lang="pascal">
function ExpandRanges(ranges : String) : array of Integer;
function ExpandRanges(ranges : String) : array of Integer;
begin
begin
Line 1,415: Line 1,415:
var expanded := ExpandRanges('-6,-3--1,3-5,7-11,14,15,17-20');
var expanded := ExpandRanges('-6,-3--1,3-5,7-11,14,15,17-20');
PrintLn(JSON.Stringify(expanded));
PrintLn(JSON.Stringify(expanded));
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>[-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20]</pre>
<pre>[-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20]</pre>
Line 1,423: Line 1,423:
{{trans|Go}}
{{trans|Go}}


<lang dyalect>func main() {
<syntaxhighlight lang="dyalect">func main() {
let input = "-6,-3--1,3-5,7-11,14,15,17-20"
let input = "-6,-3--1,3-5,7-11,14,15,17-20"
print("range: \(input)")
print("range: \(input)")
Line 1,458: Line 1,458:
}
}
main()</lang>
main()</syntaxhighlight>


{{out}}
{{out}}
Line 1,466: Line 1,466:


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
;; parsing [spaces][-]digit(s)-[-]digit(s)[spaces]
;; parsing [spaces][-]digit(s)-[-]digit(s)[spaces]
(define R (make-regexp "^ *(\-?\\d+)\-(\-?\\d+) *$" ))
(define R (make-regexp "^ *(\-?\\d+)\-(\-?\\d+) *$" ))
Line 1,492: Line 1,492:
(ranges task)
(ranges task)
→ (-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20)
→ (-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20)
</syntaxhighlight>
</lang>


=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang elixir>defmodule RC do
<syntaxhighlight lang="elixir">defmodule RC do
def expansion(range) do
def expansion(range) do
Enum.flat_map(String.split(range, ","), fn part ->
Enum.flat_map(String.split(range, ","), fn part ->
Line 1,507: Line 1,507:
end
end


IO.inspect RC.expansion("-6,-3--1,3-5,7-11,14,15,17-20")</lang>
IO.inspect RC.expansion("-6,-3--1,3-5,7-11,14,15,17-20")</syntaxhighlight>


{{out}}
{{out}}
Line 1,515: Line 1,515:


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( range ).
-module( range ).


Line 1,530: Line 1,530:
expansion_individual( {ok, [N], []} ) -> N;
expansion_individual( {ok, [N], []} ) -> N;
expansion_individual( {ok, [Start], "-" ++ Stop_string} ) -> lists:seq( Start, erlang:list_to_integer(Stop_string) ).
expansion_individual( {ok, [Start], "-" ++ Stop_string} ) -> lists:seq( Start, erlang:list_to_integer(Stop_string) ).
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,539: Line 1,539:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>open System.Text.RegularExpressions
<syntaxhighlight lang="fsharp">open System.Text.RegularExpressions


// simplify regex matching with an active pattern
// simplify regex matching with an active pattern
Line 1,561: Line 1,561:
|> List.collect parseRange
|> List.collect parseRange


printfn "%A" (expand "-6,-3--1,3-5,7-11,14,15,17-20")</lang>
printfn "%A" (expand "-6,-3--1,3-5,7-11,14,15,17-20")</syntaxhighlight>
{{out}}
{{out}}
<pre>[-6; -3; -2; -1; 3; 4; 5; 7; 8; 9; 10; 11; 14; 15; 17; 18; 19; 20]</pre>
<pre>[-6; -3; -2; -1; 3; 4; 5; 7; 8; 9; 10; 11; 14; 15; 17; 18; 19; 20]</pre>
Line 1,567: Line 1,567:
=={{header|Factor}}==
=={{header|Factor}}==
<code>R/ (?<=\d)-/ re-split</code> says: ''split only on hyphens immediately preceded by a digit.''
<code>R/ (?<=\d)-/ re-split</code> says: ''split only on hyphens immediately preceded by a digit.''
<lang factor>USING: kernel math.parser math.ranges prettyprint regexp
<syntaxhighlight lang="factor">USING: kernel math.parser math.ranges prettyprint regexp
sequences sequences.extras splitting ;
sequences sequences.extras splitting ;


Line 1,576: Line 1,576:
] map-concat ;
] map-concat ;


"-6,-3--1,3-5,7-11,14,15,17-20" expand .</lang>
"-6,-3--1,3-5,7-11,14,15,17-20" expand .</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,583: Line 1,583:


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: >snumber ( str len -- 'str 'len n )
<syntaxhighlight lang="forth">: >snumber ( str len -- 'str 'len n )
0. 2swap
0. 2swap
over c@ [char] - = if
over c@ [char] - = if
Line 1,607: Line 1,607:
repeat 2drop ;
repeat 2drop ;


s" -6,-3--1,3-5,7-11,14,15,17-20" expand</lang>
s" -6,-3--1,3-5,7-11,14,15,17-20" expand</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 1,618: Line 1,618:
A frustrating problem with many modern computer languages is the absence of a "shortcut" evaluation praxis for logical expressions; in Fortran's case the modern standard is that there is no standard. So a test <code>I<=LEN(TEXT) & TEXT(I:I)''etc.''</code> can't be relied upon to dodge out-of-bounds errors, and a flabby two-statement sequence is required instead. Similarly, few Fortran compilers allow for a function being evaluated via a WRITE statement to itself succeed in using a WRITE statement internally, though some do if one usage is free-format and the other formatted. If necessary, subroutine SPLOT could be re-written to convert an integer to a digit string without a WRITE statement, even for negative integers. And some compilers have difficulty with the use of the function name as a variable within the function so that it is safest to develop the result in an ordinary variable and then remember to assign its value to the function name just before exit.
A frustrating problem with many modern computer languages is the absence of a "shortcut" evaluation praxis for logical expressions; in Fortran's case the modern standard is that there is no standard. So a test <code>I<=LEN(TEXT) & TEXT(I:I)''etc.''</code> can't be relied upon to dodge out-of-bounds errors, and a flabby two-statement sequence is required instead. Similarly, few Fortran compilers allow for a function being evaluated via a WRITE statement to itself succeed in using a WRITE statement internally, though some do if one usage is free-format and the other formatted. If necessary, subroutine SPLOT could be re-written to convert an integer to a digit string without a WRITE statement, even for negative integers. And some compilers have difficulty with the use of the function name as a variable within the function so that it is safest to develop the result in an ordinary variable and then remember to assign its value to the function name just before exit.


A single number is made internally into a two-number range sequence, which values are used as the bounds for a DO-loop to generate the numbers for output. Despite the '''The range syntax is to be used only for, and for every range that expands to more than two values''', I see no reason for this restriction (say because otherwise some fancy method would be stymied, except I can think of no such fancier method) and I have no desire to interpose some sort of error message, a tedious business that requires a wider interface between a routine and its caller. Similarly, if a range of 40-30 were to appear, why not take it at face value? <lang Fortran> MODULE HOMEONTHERANGE
A single number is made internally into a two-number range sequence, which values are used as the bounds for a DO-loop to generate the numbers for output. Despite the '''The range syntax is to be used only for, and for every range that expands to more than two values''', I see no reason for this restriction (say because otherwise some fancy method would be stymied, except I can think of no such fancier method) and I have no desire to interpose some sort of error message, a tedious business that requires a wider interface between a routine and its caller. Similarly, if a range of 40-30 were to appear, why not take it at face value? <syntaxhighlight lang="fortran"> MODULE HOMEONTHERANGE
CONTAINS !The key function.
CONTAINS !The key function.
CHARACTER*200 FUNCTION ERANGE(TEXT) !Expands integer ranges in a list.
CHARACTER*200 FUNCTION ERANGE(TEXT) !Expands integer ranges in a list.
Line 1,717: Line 1,717:
SOME = ERANGE(SOME)
SOME = ERANGE(SOME)
WRITE (6,*) SOME !If ERANGE(SOME) then the function usually can't write output also.
WRITE (6,*) SOME !If ERANGE(SOME) then the function usually can't write output also.
END</lang>
END</syntaxhighlight>


Output: <pre> -6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20</pre>
Output: <pre> -6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20</pre>
Line 1,724: Line 1,724:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Sub split (s As Const String, sepList As Const String, result() As String)
Sub split (s As Const String, sepList As Const String, result() As String)
Line 1,798: Line 1,798:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 1,807: Line 1,807:
=={{header|Go}}==
=={{header|Go}}==
A version rather strict with input
A version rather strict with input
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,870: Line 1,870:
}
}
fmt.Println("expanded:", r)
fmt.Println("expanded:", r)
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
Line 1,880: Line 1,880:
# express as a string
# express as a string
# unwrap the list delimiters
# unwrap the list delimiters
<lang groovy>def expandRanges = { compressed ->
<syntaxhighlight lang="groovy">def expandRanges = { compressed ->
Eval.me('['+compressed.replaceAll(~/(\d)-/, '$1..')+']').flatten().toString()[1..-2]
Eval.me('['+compressed.replaceAll(~/(\d)-/, '$1..')+']').flatten().toString()[1..-2]
}</lang>
}</syntaxhighlight>
Test:
Test:
<lang groovy>def s = '-6,-3--1,3-5,7-11,14,15,17-20'
<syntaxhighlight lang="groovy">def s = '-6,-3--1,3-5,7-11,14,15,17-20'
println (expandRanges(s))</lang>
println (expandRanges(s))</syntaxhighlight>
{{out}}
{{out}}
<pre>-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20</pre>
<pre>-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20</pre>
Line 1,891: Line 1,891:
=={{header|Haskell}}==
=={{header|Haskell}}==
Given either of the below implementations of <code>expandRange</code>:
Given either of the below implementations of <code>expandRange</code>:
<lang haskell>> expandRange "-6,-3--1,3-5,7-11,14,15,17-20"
<syntaxhighlight lang="haskell">> expandRange "-6,-3--1,3-5,7-11,14,15,17-20"
[-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20]</lang>
[-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20]</syntaxhighlight>
===With conventional list processing===
===With conventional list processing===
<lang haskell>expandRange :: String -> [Int]
<syntaxhighlight lang="haskell">expandRange :: String -> [Int]
expandRange = concatMap f . split ','
expandRange = concatMap f . split ','
where f str@(c : cs) | '-' `elem` cs = [read (c : a) .. read b]
where f str@(c : cs) | '-' `elem` cs = [read (c : a) .. read b]
Line 1,903: Line 1,903:
split delim [] = []
split delim [] = []
split delim l = a : split delim (dropWhile (== delim) b)
split delim l = a : split delim (dropWhile (== delim) b)
where (a, b) = break (== delim) l</lang>
where (a, b) = break (== delim) l</syntaxhighlight>
===With a parser===
===With a parser===
<lang haskell>{-# LANGUAGE FlexibleContexts #-}
<syntaxhighlight lang="haskell">{-# LANGUAGE FlexibleContexts #-}


import Text.Parsec
import Text.Parsec
Line 1,931: Line 1,931:


main :: IO ()
main :: IO ()
main = print $ expandRange "-6,-3--1,3-5,7-11,14,15,17-20"</lang>
main = print $ expandRange "-6,-3--1,3-5,7-11,14,15,17-20"</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Just [-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20]</pre>
<pre>Just [-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20]</pre>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
s := "-6,-3--1,3-5,7-11,14,15,17-20"
s := "-6,-3--1,3-5,7-11,14,15,17-20"
write("Input string := ",s)
write("Input string := ",s)
Line 1,960: Line 1,960:
every (s := "[ ") ||:= !L || " "
every (s := "[ ") ||:= !L || " "
return s || "]"
return s || "]"
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>Input string := -6,-3--1,3-5,7-11,14,15,17-20
<pre>Input string := -6,-3--1,3-5,7-11,14,15,17-20
Line 1,966: Line 1,966:


=={{header|J}}==
=={{header|J}}==
<lang j>require'strings'
<syntaxhighlight lang="j">require'strings'
thru=: <. + i.@(+*)@-~
thru=: <. + i.@(+*)@-~
num=: _&".
num=: _&".
normaliz=: rplc&(',-';',_';'--';'-_')@,~&','
normaliz=: rplc&(',-';',_';'--';'-_')@,~&','
subranges=:<@(thru/)@(num;._2)@,&'-';._1
subranges=:<@(thru/)@(num;._2)@,&'-';._1
rngexp=: ;@subranges@normaliz</lang>
rngexp=: ;@subranges@normaliz</syntaxhighlight>
{{out|Example}}
{{out|Example}}
<lang j> rngexp '-6,-3--1,3-5,7-11,14,15,17-20'
<syntaxhighlight lang="j"> rngexp '-6,-3--1,3-5,7-11,14,15,17-20'
_6 _3 _2 _1 3 4 5 7 8 9 10 11 14 15 17 18 19 20</lang>
_6 _3 _2 _1 3 4 5 7 8 9 10 11 14 15 17 18 19 20</syntaxhighlight>


Notes:
Notes:
Line 1,991: Line 1,991:


=={{header|Java}}==
=={{header|Java}}==
<lang java>import java.util.*;
<syntaxhighlight lang="java">import java.util.*;


class RangeExpander implements Iterator<Integer>, Iterable<Integer> {
class RangeExpander implements Iterator<Integer>, Iterable<Integer> {
Line 2,055: Line 2,055:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 2,061: Line 2,061:
===Imperative (Spidermonkey)===
===Imperative (Spidermonkey)===


<lang javascript>#!/usr/bin/env js
<syntaxhighlight lang="javascript">#!/usr/bin/env js


function main() {
function main() {
Line 2,095: Line 2,095:


main();
main();
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,104: Line 2,104:
====ES5====
====ES5====


<lang JavaScript>(function (strTest) {
<syntaxhighlight lang="javascript">(function (strTest) {
'use strict';
'use strict';


Line 2,142: Line 2,142:
return expansion(strTest);
return expansion(strTest);


})('-6,-3--1,3-5,7-11,14,15,17-20');</lang>
})('-6,-3--1,3-5,7-11,14,15,17-20');</syntaxhighlight>


{{Out}}
{{Out}}


<lang JavaScript>[-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]</lang>
<syntaxhighlight lang="javascript">[-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]</syntaxhighlight>




====ES6====
====ES6====
<lang javascript>(() => {
<syntaxhighlight lang="javascript">(() => {
"use strict";
"use strict";


Line 2,213: Line 2,213:
// MAIN ---
// MAIN ---
return JSON.stringify(main());
return JSON.stringify(main());
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20]</pre>
<pre>[-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20]</pre>
Line 2,219: Line 2,219:
=={{header|jq}}==
=={{header|jq}}==
{{works with|jq|with regex support}}
{{works with|jq|with regex support}}
<lang jq>def expand_range:
<syntaxhighlight lang="jq">def expand_range:
def number: "-?[0-9]+";
def number: "-?[0-9]+";
def expand: [range(.[0]; .[1] + 1)];
def expand: [range(.[0]; .[1] + 1)];
Line 2,229: Line 2,229:
else sub( "(?<x>\(number))-(?<y>\(number))"; "\(.x):\(.y)")
else sub( "(?<x>\(number))-(?<y>\(number))"; "\(.x):\(.y)")
| split(":") | map(tonumber) | expand
| split(":") | map(tonumber) | expand
end));</lang>
end));</syntaxhighlight>
'''Example''':
'''Example''':
<lang jq>"-6,-3--1,3-5,7-11,14,15,17-20" | expand_range</lang>
<syntaxhighlight lang="jq">"-6,-3--1,3-5,7-11,14,15,17-20" | expand_range</syntaxhighlight>
{{out}}$ jq -c -n -f Range_expansion.jq
{{out}}$ jq -c -n -f Range_expansion.jq
[-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20]
[-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20]
Line 2,237: Line 2,237:
=={{header|Jsish}}==
=={{header|Jsish}}==
{{trans|Javascript}}
{{trans|Javascript}}
<lang javascript>#!/usr/bin/env jsish
<syntaxhighlight lang="javascript">#!/usr/bin/env jsish
"use strict";
"use strict";


Line 2,276: Line 2,276:
rangeExpand('-6,-3--1,3-5,7-11,14,15,17-20') ==> [ -6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 ]
rangeExpand('-6,-3--1,3-5,7-11,14,15,17-20') ==> [ -6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 ]
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


{{out}}
{{out}}
Line 2,283: Line 2,283:


=={{header|Julia}}==
=={{header|Julia}}==
<lang Julia>slurp(s) = readcsv(IOBuffer(s))
<syntaxhighlight lang="julia">slurp(s) = readcsv(IOBuffer(s))


conv(s)= colon(map(x->parse(Int,x),match(r"^(-?\d+)-(-?\d+)$", s).captures)...)
conv(s)= colon(map(x->parse(Int,x),match(r"^(-?\d+)-(-?\d+)$", s).captures)...)


expand(s) = mapreduce(x -> isa(x,Number)? Int(x) : conv(x), vcat, slurp(s))</lang>
expand(s) = mapreduce(x -> isa(x,Number)? Int(x) : conv(x), vcat, slurp(s))</syntaxhighlight>
{{out}}
{{out}}
<pre>julia> show(expand("-6,-3--1,3-5,7-11,14,15,17-20"))
<pre>julia> show(expand("-6,-3--1,3-5,7-11,14,15,17-20"))
Line 2,293: Line 2,293:


=={{header|K}}==
=={{header|K}}==
<lang k>grp : {1_'(&x=*x)_ x:",",x}
<syntaxhighlight lang="k">grp : {1_'(&x=*x)_ x:",",x}
pos : {:[3=l:#p:&"-"=x;0,p@1;2=l;p;0=*p;,0;0,p]}
pos : {:[3=l:#p:&"-"=x;0,p@1;2=l;p;0=*p;,0;0,p]}
conv: 0${(x;1_ y)}/'{(pos x)_ x}'
conv: 0${(x;1_ y)}/'{(pos x)_ x}'
expd: {,/@[x;&2=#:'x;{(*x)+!1+,/-':x}]}
expd: {,/@[x;&2=#:'x;{(*x)+!1+,/-':x}]}
rnge: {expd@conv grp x}</lang>
rnge: {expd@conv grp x}</syntaxhighlight>
{{out|Example}}
{{out|Example}}
<lang k> rnge "-6,-3--1,3-5,7-11,14,15,17-20"
<syntaxhighlight lang="k"> rnge "-6,-3--1,3-5,7-11,14,15,17-20"
-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20</lang>
-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun expandRange(s: String): MutableList<Int> {
fun expandRange(s: String): MutableList<Int> {
Line 2,337: Line 2,337:
val s = "-6,-3--1,3-5,7-11,14,15,17-20"
val s = "-6,-3--1,3-5,7-11,14,15,17-20"
println(expandRange(s))
println(expandRange(s))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,345: Line 2,345:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang lasso>define range_expand(expression::string) => {
<syntaxhighlight lang="lasso">define range_expand(expression::string) => {
local(parts) = regexp(`^(-?\d+)-(-?\d+)$`)
local(parts) = regexp(`^(-?\d+)-(-?\d+)$`)
Line 2,357: Line 2,357:
}
}


range_expand(`-6,-3--1,3-5,7-11,14,15,17-20`)</lang>
range_expand(`-6,-3--1,3-5,7-11,14,15,17-20`)</syntaxhighlight>


{{out}}
{{out}}
Line 2,363: Line 2,363:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>print ExpandRange$( "-6,-3--1,3-5,7-11,14,15,17-20")
<syntaxhighlight lang="lb">print ExpandRange$( "-6,-3--1,3-5,7-11,14,15,17-20")
end
end


Line 2,385: Line 2,385:
ItemCount = ItemCount + 1
ItemCount = ItemCount + 1
wend
wend
end function</lang>
end function</syntaxhighlight>
{{out}}
{{out}}
<pre>-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20</pre>
<pre>-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20</pre>


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>-- Note: currently does not support extra white space in input string
<syntaxhighlight lang="lingo">-- Note: currently does not support extra white space in input string
on expandRange (str)
on expandRange (str)
res = ""
res = ""
Line 2,410: Line 2,410:
delete the last char of res
delete the last char of res
return res
return res
end</lang>
end</syntaxhighlight>
<lang lingo>put expandRange("-6,-3--1,3-5,7-11,14,15,17-20")
<syntaxhighlight lang="lingo">put expandRange("-6,-3--1,3-5,7-11,14,15,17-20")
-- "-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20"</lang>
-- "-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20"</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
<lang LiveCode>function range beginning ending stepping
<syntaxhighlight lang="livecode">function range beginning ending stepping
local tRange, tBegin, tEnd, tstep
local tRange, tBegin, tEnd, tstep
if stepping is empty or stepping is 0 then
if stepping is empty or stepping is 0 then
Line 2,452: Line 2,452:
end repeat
end repeat
return z
return z
end expandRange</lang>
end expandRange</syntaxhighlight>


Test
Test
<lang LiveCode>expandRange("-6,-3--1,3-5,7-11,14,15,17-20")
<syntaxhighlight lang="livecode">expandRange("-6,-3--1,3-5,7-11,14,15,17-20")
-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20 </lang>
-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20 </syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==


<lang lua>function range(i, j)
<syntaxhighlight lang="lua">function range(i, j)
local t = {}
local t = {}
for n = i, j, i<j and 1 or -1 do
for n = i, j, i<j and 1 or -1 do
Line 2,487: Line 2,487:


local ranges = "-6,-3--1,3-5,7-11,14,15,17-20"
local ranges = "-6,-3--1,3-5,7-11,14,15,17-20"
print(table.concat(expand_ranges(ranges), ', '))</lang>
print(table.concat(expand_ranges(ranges), ', '))</syntaxhighlight>


Due to the way Lua's <code>tonumber</code> function works and the way the string pattern to parse ranges is written, whitespace is allowed around commas and the dash separating the range start and end (but not between the plus/minus sign and the number).
Due to the way Lua's <code>tonumber</code> function works and the way the string pattern to parse ranges is written, whitespace is allowed around commas and the dash separating the range start and end (but not between the plus/minus sign and the number).
Line 2,497: Line 2,497:


=={{header|Maple}}==
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
ExpandRanges := proc( s :: string )
ExpandRanges := proc( s :: string )
uses StringTools;
uses StringTools;
Line 2,535: Line 2,535:
map( DoOne, map( Trim, Split( s, "," ) ) )
map( DoOne, map( Trim, Split( s, "," ) ) )
end proc:
end proc:
</syntaxhighlight>
</lang>
Running this on the example input we get the following.
Running this on the example input we get the following.
<syntaxhighlight lang="maple">
<lang Maple>
> rng := "-6,-3--1,3-5,7-11,14,15,17-20":
> rng := "-6,-3--1,3-5,7-11,14,15,17-20":
> ExpandRanges( rng );
> ExpandRanges( rng );
[-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]
[-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]
</syntaxhighlight>
</lang>
Here is an additional example which my first attempt got wrong.
Here is an additional example which my first attempt got wrong.
<syntaxhighlight lang="maple">
<lang Maple>
> rng := "-6,-3-1,3-5,7-11,14,15,17-20":
> rng := "-6,-3-1,3-5,7-11,14,15,17-20":
> ExpandRanges( rng );
> ExpandRanges( rng );
[-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]
[-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]
</syntaxhighlight>
</lang>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>rangeexpand[ rng_ ] := Module[ { step1 },
<syntaxhighlight lang="mathematica">rangeexpand[ rng_ ] := Module[ { step1 },
step1 = StringSplit[StringReplacePart[rng,"S",StringPosition[ rng,DigitCharacter~~"-"] /. {x_,y_} -> {y,y}],","];
step1 = StringSplit[StringReplacePart[rng,"S",StringPosition[ rng,DigitCharacter~~"-"] /. {x_,y_} -> {y,y}],","];
Flatten@ToExpression/@Quiet@StringReplace[step1,x__~~"S"~~y__->"Range["<>x<>","<>y<>"]"] ]</lang>
Flatten@ToExpression/@Quiet@StringReplace[step1,x__~~"S"~~y__->"Range["<>x<>","<>y<>"]"] ]</syntaxhighlight>
{{out|Example}}
{{out|Example}}
<pre>rangeexpand["-6,-3--1,3-5,7-11,14,15,17-20"]
<pre>rangeexpand["-6,-3--1,3-5,7-11,14,15,17-20"]
Line 2,558: Line 2,558:


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<lang MATLAB>function L=range_expansion(S)
<syntaxhighlight lang="matlab">function L=range_expansion(S)
% Range expansion
% Range expansion
if nargin < 1;
if nargin < 1;
Line 2,570: Line 2,570:
S(ixr)=':';
S(ixr)=':';
S=['[',S,']'];
S=['[',S,']'];
L=eval(S);</lang>
L=eval(S);</syntaxhighlight>
Usage:
Usage:
<pre>
<pre>
Line 2,580: Line 2,580:


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>pullInt = function(chars)
<syntaxhighlight lang="miniscript">pullInt = function(chars)
numstr = chars.pull
numstr = chars.pull
while chars and chars[0] != "," and chars[0] != "-"
while chars and chars[0] != "," and chars[0] != "-"
Line 2,603: Line 2,603:
end function
end function


print expandRange("-6,-3--1,3-5,7-11,14,15,17-20")</lang>
print expandRange("-6,-3--1,3-5,7-11,14,15,17-20")</syntaxhighlight>
{{out}}
{{out}}
<pre>[-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]</pre>
<pre>[-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]</pre>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<lang MUMPS>RANGEXP(X) ;Integer range expansion
<syntaxhighlight lang="mumps">RANGEXP(X) ;Integer range expansion
NEW Y,I,J,X1,H SET Y=""
NEW Y,I,J,X1,H SET Y=""
FOR I=1:1:$LENGTH(X,",") DO
FOR I=1:1:$LENGTH(X,",") DO
Line 2,617: Line 2,617:
.IF '(H<0) FOR J=+$EXTRACT(X1,1,(H-1)):1:+$EXTRACT(X1,(H+1),$LENGTH(X1)) SET Y=$SELECT($LENGTH(Y)=0:J,1:Y_","_J)
.IF '(H<0) FOR J=+$EXTRACT(X1,1,(H-1)):1:+$EXTRACT(X1,(H+1),$LENGTH(X1)) SET Y=$SELECT($LENGTH(Y)=0:J,1:Y_","_J)
KILL I,J,X1,H
KILL I,J,X1,H
QUIT Y</lang>
QUIT Y</syntaxhighlight>
{{out|Example}}
{{out|Example}}
<pre>USER>SET U="-6,-3--1,3-5,7-11,14,15,17-20"
<pre>USER>SET U="-6,-3--1,3-5,7-11,14,15,17-20"
Line 2,626: Line 2,626:
=={{header|NetRexx}}==
=={{header|NetRexx}}==
Translation of: [[Range_expansion#Version_2_somewhat_simplified_.21.3F.21|Rexx Version 2]]
Translation of: [[Range_expansion#Version_2_somewhat_simplified_.21.3F.21|Rexx Version 2]]
<lang NetRexx>/*NetRexx program to expand a range of integers into a list. *************
<syntaxhighlight lang="netrexx">/*NetRexx program to expand a range of integers into a list. *************
* 09.08.2012 Walter Pachl derived from my Rexx version
* 09.08.2012 Walter Pachl derived from my Rexx version
* Changes: translate(old,' ',',') -> old.translate(' ',',')
* Changes: translate(old,' ',',') -> old.translate(' ',',')
Line 2,660: Line 2,660:
End
End
Say 'new='new /*show the expanded list */
Say 'new='new /*show the expanded list */
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,668: Line 2,668:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import parseutils, strutils
<syntaxhighlight lang="nim">import parseutils, strutils


proc expandRange(input: string): string =
proc expandRange(input: string): string =
Line 2,691: Line 2,691:
return output.join(",")
return output.join(",")


echo("-6,-3--1,3-5,7-11,14,15,17-20".expandRange)</lang>
echo("-6,-3--1,3-5,7-11,14,15,17-20".expandRange)</syntaxhighlight>


{{out}}
{{out}}
Line 2,698: Line 2,698:
=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
Oxford Oberon-2
Oxford Oberon-2
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE LIVector;
MODULE LIVector;
IMPORT SYSTEM;
IMPORT SYSTEM;
Line 2,935: Line 2,935:
END ExpandRange.
END ExpandRange.


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,942: Line 2,942:


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>#load "str.cma"
<syntaxhighlight lang="ocaml">#load "str.cma"


let range a b =
let range a b =
Line 2,964: Line 2,964:
let exp = range_expand rng in
let exp = range_expand rng in
List.iter (Printf.printf " %d") exp;
List.iter (Printf.printf " %d") exp;
print_newline ()</lang>
print_newline ()</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
<lang oforth>: addRange( s res -- )
<syntaxhighlight lang="oforth">: addRange( s res -- )
| i n |
| i n |
s asInteger dup ifNotNull: [ res add return ] drop
s asInteger dup ifNotNull: [ res add return ] drop
Line 2,976: Line 2,976:


: rangeExpand ( s -- [ n ] )
: rangeExpand ( s -- [ n ] )
ArrayBuffer new s wordsWith( ',' ) apply( #[ over addRange ] ) ;</lang>
ArrayBuffer new s wordsWith( ',' ) apply( #[ over addRange ] ) ;</syntaxhighlight>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
list = '-6,-3--1,3-5,7-11,14,15,17-20'
list = '-6,-3--1,3-5,7-11,14,15,17-20'
expanded = expandRanges(list)
expanded = expandRanges(list)
Line 3,010: Line 3,010:
end
end
return expanded
return expanded
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,018: Line 3,018:


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
fun {Expand RangeDesc}
fun {Expand RangeDesc}
{Flatten
{Flatten
Line 3,047: Line 3,047:
in
in
{System.showInfo
{System.showInfo
{Value.toVirtualString {Expand "-6,-3--1,3-5,7-11,14,15,17-20"} 100 100}}</lang>
{Value.toVirtualString {Expand "-6,-3--1,3-5,7-11,14,15,17-20"} 100 100}}</syntaxhighlight>
{{out|Sample output}}
{{out|Sample output}}
<lang oz>[~6 ~3 ~2 ~1 3 4 5 7 8 9 10 11 14 15 17 18 19 20]</lang>
<syntaxhighlight lang="oz">[~6 ~3 ~2 ~1 3 4 5 7 8 9 10 11 14 15 17 18 19 20]</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
One-liner:
One-liner:
<lang Perl>sub rangex {
<syntaxhighlight lang="perl">sub rangex {
map { /^(.*\d)-(.+)$/ ? $1..$2 : $_ } split /,/, shift
map { /^(.*\d)-(.+)$/ ? $1..$2 : $_ } split /,/, shift
}
}


# Test and display
# Test and display
print join(',', rangex('-6,-3--1,3-5,7-11,14,15,17-20')), "\n";</lang>
print join(',', rangex('-6,-3--1,3-5,7-11,14,15,17-20')), "\n";</syntaxhighlight>
{{out}}
{{out}}
<pre>-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20</pre>
<pre>-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20</pre>


Alternative:
Alternative:
<lang Perl>sub rangex {
<syntaxhighlight lang="perl">sub rangex {
(my $range = shift) =~ s/(?<=\d)-/../g;
(my $range = shift) =~ s/(?<=\d)-/../g;
eval $range;
eval $range;
}</lang>
}</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<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;">function</span> <span style="color: #000000;">range_expansion</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">range</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">range_expansion</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">range</span><span style="color: #0000FF;">)</span>
Line 3,092: Line 3,092:
<span style="color: #0000FF;">?</span><span style="color: #000000;">range_expansion</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"-6,-3-1,3-5,7-11,14,15,17-20"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">range_expansion</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"-6,-3-1,3-5,7-11,14,15,17-20"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">range_expansion</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"-6,-3--1,3-5,7-11,14,15,17-20"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">range_expansion</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"-6,-3--1,3-5,7-11,14,15,17-20"</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 3,101: Line 3,101:
=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
Require Phixmonti 1.1
Require Phixmonti 1.1
<lang Phixmonti>0 tolist var r
<syntaxhighlight lang="phixmonti">0 tolist var r


def append
def append
Line 3,124: Line 3,124:
endfor
endfor
r
r
pstack</lang>
pstack</syntaxhighlight>


Other solution
Other solution
<lang Phixmonti>0 tolist var r
<syntaxhighlight lang="phixmonti">0 tolist var r


def append
def append
Line 3,149: Line 3,149:
endfor
endfor
r
r
pstack</lang>
pstack</syntaxhighlight>


A bit more understandable
A bit more understandable
<lang Phixmonti>0 tolist var r
<syntaxhighlight lang="phixmonti">0 tolist var r


def append
def append
Line 3,189: Line 3,189:
endfor
endfor
r
r
pstack</lang>
pstack</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
{{trans|Python}}
{{trans|Python}}
<lang PHP>function rangex($str) {
<syntaxhighlight lang="php">function rangex($str) {
$lst = array();
$lst = array();
foreach (explode(',', $str) as $e) {
foreach (explode(',', $str) as $e) {
Line 3,204: Line 3,204:
}
}
return $lst;
return $lst;
}</lang>
}</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de rangeexpand (Str)
<syntaxhighlight lang="picolisp">(de rangeexpand (Str)
(make
(make
(for S (split (chop Str) ",")
(for S (split (chop Str) ",")
Line 3,215: Line 3,215:
(format (head @ S))
(format (head @ S))
(format (tail (- -1 @) S)) ) )
(format (tail (- -1 @) S)) ) )
(link (format S)) ) ) ) )</lang>
(link (format S)) ) ) ) )</syntaxhighlight>
{{out}}
{{out}}
<pre>: (rangeexpand "-6,-3--1,3-5,7-11,14,15,17-20")
<pre>: (rangeexpand "-6,-3--1,3-5,7-11,14,15,17-20")
Line 3,221: Line 3,221:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>range_expansion:
<syntaxhighlight lang="pl/i">range_expansion:
procedure options (main);
procedure options (main);


Line 3,271: Line 3,271:
delimiter = ',';
delimiter = ',';
end;
end;
end range_expansion;</lang>
end range_expansion;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,278: Line 3,278:


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function range-expansion($array) {
function range-expansion($array) {
function expansion($arr) {
function expansion($arr) {
Line 3,301: Line 3,301:
}
}
range-expansion "-6,-3--1,3-5,7-11,14,15,17-20"
range-expansion "-6,-3--1,3-5,7-11,14,15,17-20"
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 3,309: Line 3,309:
===Alternate Half-Assed Regex Version===
===Alternate Half-Assed Regex Version===
Ten times faster (only minimally tested).
Ten times faster (only minimally tested).
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Expand-Range
function Expand-Range
{
{
Line 3,352: Line 3,352:
$output
$output
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
(Expand-Range "-6,-3--1,3-5,7-11,14,15,17-20") -join ", "
(Expand-Range "-6,-3--1,3-5,7-11,14,15,17-20") -join ", "
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,366: Line 3,366:
The code uses three predicates '''extract_Range/2''', '''study_Range/2''' and '''pack_Range/2'''.<BR>
The code uses three predicates '''extract_Range/2''', '''study_Range/2''' and '''pack_Range/2'''.<BR>
Every predicate works in both directions arg1 towards arg2 and arg2 towards arg1, so that '''Range expansion''' and '''Range extraction''' work with the same predicates but in reverse order.
Every predicate works in both directions arg1 towards arg2 and arg2 towards arg1, so that '''Range expansion''' and '''Range extraction''' work with the same predicates but in reverse order.
<lang Prolog>range_expand :-
<syntaxhighlight lang="prolog">range_expand :-
L = '-6,-3--1,3-5,7-11,14,15,17-20',
L = '-6,-3--1,3-5,7-11,14,15,17-20',
writeln(L),
writeln(L),
Line 3,446: Line 3,446:
run(Var1,LRest,[Deb, Fin], RRest).
run(Var1,LRest,[Deb, Fin], RRest).


run(Val,[Other|RRest], [Val, Val],[Other|RRest]).</lang>
run(Val,[Other|RRest], [Val, Val],[Other|RRest]).</syntaxhighlight>
{{out}}
{{out}}
<pre> ?- range_expand.
<pre> ?- range_expand.
Line 3,454: Line 3,454:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Procedure rangeexpand(txt.s, List outputList())
<syntaxhighlight lang="purebasic">Procedure rangeexpand(txt.s, List outputList())
Protected rangesCount = CountString(txt, ",") + 1
Protected rangesCount = CountString(txt, ",") + 1
Protected subTxt.s, r, rangeMarker, rangeStart, rangeFinish, rangeIncrement, i
Protected subTxt.s, r, rangeMarker, rangeStart, rangeFinish, rangeIncrement, i
Line 3,499: Line 3,499:
Input()
Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>
{{out}}
{{out}}
<pre>[ -6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20 ]</pre>
<pre>[ -6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20 ]</pre>
Line 3,505: Line 3,505:
=={{header|Python}}==
=={{header|Python}}==
===Procedural===
===Procedural===
<lang python>def rangeexpand(txt):
<syntaxhighlight lang="python">def rangeexpand(txt):
lst = []
lst = []
for r in txt.split(','):
for r in txt.split(','):
Line 3,515: Line 3,515:
return lst
return lst


print(rangeexpand('-6,-3--1,3-5,7-11,14,15,17-20'))</lang>
print(rangeexpand('-6,-3--1,3-5,7-11,14,15,17-20'))</syntaxhighlight>


another variant, using [[regular expressions]] to parse the ranges,
another variant, using [[regular expressions]] to parse the ranges,
<lang python>import re
<syntaxhighlight lang="python">import re


def rangeexpand(txt):
def rangeexpand(txt):
Line 3,528: Line 3,528:
else:
else:
lst.append(int(start))
lst.append(int(start))
return lst</lang>
return lst</syntaxhighlight>


===Functional===
===Functional===
As a fold/catamorphism:
As a fold/catamorphism:
{{Works with|Python|3.7}}
{{Works with|Python|3.7}}
<lang python>'''Range expansion'''
<syntaxhighlight lang="python">'''Range expansion'''


from functools import (reduce)
from functools import (reduce)
Line 3,634: Line 3,634:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Range expansion:
<pre>Range expansion:
Line 3,643: Line 3,643:


=={{header|R}}==
=={{header|R}}==
<syntaxhighlight lang="r">
<lang R>
rangeExpand <- function(text) {
rangeExpand <- function(text) {
lst <- gsub("(\\d)-", "\\1:", unlist(strsplit(text, ",")))
lst <- gsub("(\\d)-", "\\1:", unlist(strsplit(text, ",")))
Line 3,651: Line 3,651:
rangeExpand("-6,-3--1,3-5,7-11,14,15,17-20")
rangeExpand("-6,-3--1,3-5,7-11,14,15,17-20")
[1] -6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20
[1] -6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 3,668: Line 3,668:


(range-expand "-6,-3--1,3-5,7-11,14,15,17-20")
(range-expand "-6,-3--1,3-5,7-11,14,15,17-20")
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,679: Line 3,679:
rather than 3 followed by - followed by -4,
rather than 3 followed by - followed by -4,
a readtable is installed that makes - a delimiter.
a readtable is installed that makes - a delimiter.
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 3,706: Line 3,706:
(range-expand (open-input-string "-6,-3--1,3-5,7-11,14,15,17-20"))
(range-expand (open-input-string "-6,-3--1,3-5,7-11,14,15,17-20"))
</syntaxhighlight>
</lang>
Note that one can use the full number syntax in this alternative version:
Note that one can use the full number syntax in this alternative version:
<pre>
<pre>
Line 3,717: Line 3,717:


{{works with|Rakudo|2016.07}}
{{works with|Rakudo|2016.07}}
<lang perl6>sub range-expand (Str $range-description) {
<syntaxhighlight lang="raku" line>sub range-expand (Str $range-description) {
my token number { '-'? \d+ }
my token number { '-'? \d+ }
my token range { (<&number>) '-' (<&number>) }
my token range { (<&number>) '-' (<&number>) }
Line 3,727: Line 3,727:
}
}
say range-expand('-6,-3--1,3-5,7-11,14,15,17-20').join(', ');</lang>
say range-expand('-6,-3--1,3-5,7-11,14,15,17-20').join(', ');</syntaxhighlight>


{{out}}
{{out}}
Line 3,735: Line 3,735:
Alternatively, using a grammar:
Alternatively, using a grammar:


<lang perl6>grammar RangeList {
<syntaxhighlight lang="raku" line>grammar RangeList {
token TOP { <term>* % ',' { make $<term>.map(*.made) } }
token TOP { <term>* % ',' { make $<term>.map(*.made) } }
token term { [<range>|<num>] { make ($<num> // $<range>).made } }
token term { [<range>|<num>] { make ($<num> // $<range>).made } }
Line 3,742: Line 3,742:
}
}


say RangeList.parse('-6,-3--1,3-5,7-11,14,15,17-20').made.flat.join(', ');</lang>
say RangeList.parse('-6,-3--1,3-5,7-11,14,15,17-20').made.flat.join(', ');</syntaxhighlight>


{{out}}
{{out}}
Line 3,749: Line 3,749:
=={{header|Raven}}==
=={{header|Raven}}==
Based loosely on Ruby
Based loosely on Ruby
<lang raven>define get_num use $lst
<syntaxhighlight lang="raven">define get_num use $lst
# "-22" split by "-" is [ "", "22" ] so check if
# "-22" split by "-" is [ "", "22" ] so check if
# first list item is "" -> a negative number
# first list item is "" -> a negative number
Line 3,781: Line 3,781:
"\n" print
"\n" print


'-6,-3--1,3-5,7-11,14,15,17-20' range_expand</lang>
'-6,-3--1,3-5,7-11,14,15,17-20' range_expand</syntaxhighlight>
{{out}}
{{out}}
<pre>-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20</pre>
<pre>-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20</pre>
Line 3,788: Line 3,788:
===version 1===
===version 1===
Extra imbedded blanks were added to the &nbsp; old &nbsp; list (which are ignored) to make the &nbsp; ''over/under'' &nbsp; comparison easier &nbsp; (in the output).
Extra imbedded blanks were added to the &nbsp; old &nbsp; list (which are ignored) to make the &nbsp; ''over/under'' &nbsp; comparison easier &nbsp; (in the output).
<lang rexx>/*REXX program expands an ordered list of integers into an expanded list. */
<syntaxhighlight lang="rexx">/*REXX program expands an ordered list of integers into an expanded list. */
old= '-6,-3--1, 3-5, 7-11, 14,15,17-20'; a=translate(old,,',')
old= '-6,-3--1, 3-5, 7-11, 14,15,17-20'; a=translate(old,,',')
new= /*translate [↑] commas (,) ───► blanks*/
new= /*translate [↑] commas (,) ───► blanks*/
Line 3,800: Line 3,800:
new=translate( strip(new), ',', " ") /*remove the first blank, add commas. */
new=translate( strip(new), ',', " ") /*remove the first blank, add commas. */
say 'old list: ' old /*show the old list of numbers/ranges.*/
say 'old list: ' old /*show the old list of numbers/ranges.*/
say 'new list: ' new /* " " new " " numbers. */</lang>
say 'new list: ' new /* " " new " " numbers. */</syntaxhighlight>
'''output'''
'''output'''
<pre>
<pre>
Line 3,808: Line 3,808:


===Version 2 somewhat simplified !?!===
===Version 2 somewhat simplified !?!===
<lang rexx>/*REXX program to expand a range of integers into a list. *************
<syntaxhighlight lang="rexx">/*REXX program to expand a range of integers into a list. *************
* 09.08.2012 Walter Pachl
* 09.08.2012 Walter Pachl
**********************************************************************/
**********************************************************************/
Line 3,836: Line 3,836:
End
End
End
End
Say 'new='new /*show the expanded list */</lang>
Say 'new='new /*show the expanded list */</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,844: Line 3,844:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Range expansion
# Project : Range expansion


Line 3,886: Line 3,886:
see svect
see svect
see "]" + nl
see "]" + nl
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 3,893: Line 3,893:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>def range_expand(rng)
<syntaxhighlight lang="ruby">def range_expand(rng)
rng.split(',').flat_map do |part|
rng.split(',').flat_map do |part|
if part =~ /^(-?\d+)-(-?\d+)$/
if part =~ /^(-?\d+)-(-?\d+)$/
Line 3,903: Line 3,903:
end
end


p range_expand('-6,-3--1,3-5,7-11,14,15,17-20')</lang>
p range_expand('-6,-3--1,3-5,7-11,14,15,17-20')</syntaxhighlight>
{{out}}
{{out}}
<pre>[-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]</pre>
<pre>[-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]</pre>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>PRINT rangeExpand$("-6,-3--1,3-5,7-11,14,15,17-20")
<syntaxhighlight lang="runbasic">PRINT rangeExpand$("-6,-3--1,3-5,7-11,14,15,17-20")
end
end


Line 3,932: Line 3,932:
if i <> 0 then goto [loop]
if i <> 0 then goto [loop]
rangeExpand$ = range$
rangeExpand$ = range$
end function</lang>
end function</syntaxhighlight>
{{out}}
{{out}}
<pre>-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20</pre>
<pre>-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20</pre>
Line 3,939: Line 3,939:
Rust doesn't have regex in standard library yet.
Rust doesn't have regex in standard library yet.


<lang rust>use std::str::FromStr;
<syntaxhighlight lang="rust">use std::str::FromStr;


// Precondition: range doesn't contain multibyte UTF-8 characters
// Precondition: range doesn't contain multibyte UTF-8 characters
Line 3,965: Line 3,965:
println!("{:?}", range_expand("-6,-3--1,3-5,7-11,14,15,17-20"));
println!("{:?}", range_expand("-6,-3--1,3-5,7-11,14,15,17-20"));
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,973: Line 3,973:


=={{header|S-lang}}==
=={{header|S-lang}}==
<lang S-lang>variable r_expres = "-6,-3--1,3-5,7-11,14,15,17-20", s, r_expan = {}, dpos, i;
<syntaxhighlight lang="s-lang">variable r_expres = "-6,-3--1,3-5,7-11,14,15,17-20", s, r_expan = {}, dpos, i;


foreach s (strchop(r_expres, ',', 0))
foreach s (strchop(r_expres, ',', 0))
Line 3,991: Line 3,991:
list_append(r_expan, s);
list_append(r_expan, s);
}
}
print(strjoin(list_to_array(r_expan), ", "));</lang>
print(strjoin(list_to_array(r_expan), ", "));</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang Scala>def rangex(str: String): Seq[Int] =
<syntaxhighlight lang="scala">def rangex(str: String): Seq[Int] =
str split "," flatMap { (s) =>
str split "," flatMap { (s) =>
val r = """(-?\d+)(?:-(-?\d+))?""".r
val r = """(-?\d+)(?:-(-?\d+))?""".r
val r(a,b) = s
val r(a,b) = s
if (b == null) Seq(a.toInt) else a.toInt to b.toInt
if (b == null) Seq(a.toInt) else a.toInt to b.toInt
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 4,008: Line 4,008:


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(define split
<syntaxhighlight lang="scheme">(define split
(lambda (str char skip count)
(lambda (str char skip count)
(let ((len (string-length str)))
(let ((len (string-length str)))
Line 4,042: Line 4,042:
(display ","))))))
(display ","))))))
(split str #\, 0 0))
(split str #\, 0 0))
(newline)))</lang>
(newline)))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,052: Line 4,052:
The library [http://seed7.sourceforge.net/libraries/scanstri.htm scanstri.s7i] defines the function [http://seed7.sourceforge.net/libraries/scanstri.htm#getInteger%28inout_string%29 getInteger] to extract substrings with integer literals (optional sign followed by a sequence of digits) from a string.
The library [http://seed7.sourceforge.net/libraries/scanstri.htm scanstri.s7i] defines the function [http://seed7.sourceforge.net/libraries/scanstri.htm#getInteger%28inout_string%29 getInteger] to extract substrings with integer literals (optional sign followed by a sequence of digits) from a string.
The integer literals are converted to the type [http://seed7.sourceforge.net/libraries/integer.htm integer] with the [http://seed7.sourceforge.net/libraries/integer.htm#%28attr_integer%29parse%28in_string%29 parse] operator.
The integer literals are converted to the type [http://seed7.sourceforge.net/libraries/integer.htm integer] with the [http://seed7.sourceforge.net/libraries/integer.htm#%28attr_integer%29parse%28in_string%29 parse] operator.
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "scanstri.s7i";
include "scanstri.s7i";


Line 4,086: Line 4,086:
end for;
end for;
writeln;
writeln;
end func;</lang>
end func;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,093: Line 4,093:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func rangex(str) {
<syntaxhighlight lang="ruby">func rangex(str) {
str.split(',').map { |r|
str.split(',').map { |r|
var m = r.match(/^
var m = r.match(/^
Line 4,104: Line 4,104:
}
}


say rangex('-6,-3--1,3-5,7-11,14,15,17-20').join(',')</lang>
say rangex('-6,-3--1,3-5,7-11,14,15,17-20').join(',')</syntaxhighlight>
{{out}}
{{out}}
<pre>-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20</pre>
<pre>-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20</pre>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
<lang SNOBOL4>* # Return range n1 .. n2
<syntaxhighlight lang="snobol4">* # Return range n1 .. n2
define('range(n1,n2)') :(range_end)
define('range(n1,n2)') :(range_end)
range range = range n1 ','; n1 = lt(n1,n2) n1 + 1 :s(range)
range range = range n1 ','; n1 = lt(n1,n2) n1 + 1 :s(range)
Line 4,123: Line 4,123:
* # Test and display
* # Test and display
output = rangex('-6,-3--1,3-5,7-11,14,15,17-20')
output = rangex('-6,-3--1,3-5,7-11,14,15,17-20')
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20</pre>
<pre>-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20</pre>
Line 4,130: Line 4,130:
This is not a particularly efficient solution, but it gets the job done.
This is not a particularly efficient solution, but it gets the job done.


<syntaxhighlight lang="sql">
<lang SQL>
/*
/*
This code is an implementation of "Range expansion" in SQL ORACLE 19c
This code is an implementation of "Range expansion" in SQL ORACLE 19c
Line 4,247: Line 4,247:
;
;


</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 4,262: Line 4,262:


=={{header|Tailspin}}==
=={{header|Tailspin}}==
<lang tailspin>
<syntaxhighlight lang="tailspin">
composer expand
composer expand
[<element>*]
[<element>*]
Line 4,270: Line 4,270:


'-6,-3--1,3-5,7-11,14,15,17-20' -> expand -> !OUT::write
'-6,-3--1,3-5,7-11,14,15,17-20' -> expand -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 4,277: Line 4,277:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>proc rangeExpand desc {
<syntaxhighlight lang="tcl">proc rangeExpand desc {
set result {}
set result {}
foreach term [split $desc ","] {
foreach term [split $desc ","] {
Line 4,290: Line 4,290:
}
}


puts [rangeExpand "-6,-3--1,3-5,7-11,14,15,17-20"]</lang>
puts [rangeExpand "-6,-3--1,3-5,7-11,14,15,17-20"]</syntaxhighlight>
{{out}}
{{out}}
<pre>-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20</pre>
<pre>-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20</pre>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>$$ MODE TUSCRIPT
<syntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
rangednrs="-6,-3--1,3-5,7-11,14,15,17-20"
rangednrs="-6,-3--1,3-5,7-11,14,15,17-20"
expandnrs=SPLIT (rangednrs,":,:")
expandnrs=SPLIT (rangednrs,":,:")
Line 4,316: Line 4,316:
expandnrs= JOIN (expandnrs,",")
expandnrs= JOIN (expandnrs,",")


PRINT expandnrs</lang>
PRINT expandnrs</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,341: Line 4,341:
Code:
Code:


<lang txr>@(define num (n))@(local tok)@{tok /[+\-]?\d+/}@(bind n @(int-str tok))@(end)
<syntaxhighlight lang="txr">@(define num (n))@(local tok)@{tok /[+\-]?\d+/}@(bind n @(int-str tok))@(end)
@(define entry (e))@\
@(define entry (e))@\
@(local n1 n2)@\
@(local n1 n2)@\
Line 4,383: Line 4,383:
your junk: @{trailing-junk}
your junk: @{trailing-junk}
@(end)
@(end)
@(end)</lang>
@(end)</syntaxhighlight>


{{out|Run}}
{{out|Run}}
Line 4,407: Line 4,407:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|bash}}
{{works with|bash}}
<lang bash>#!/usr/bin/bash
<syntaxhighlight lang="bash">#!/usr/bin/bash


range_expand () (
range_expand () (
Line 4,425: Line 4,425:
)
)


range_expand "-6,-3--1,3-5,7-11,14,15,17-20"</lang>
range_expand "-6,-3--1,3-5,7-11,14,15,17-20"</syntaxhighlight>
{{out}}
{{out}}
<pre>-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20</pre>
<pre>-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20</pre>


=={{header|Ursala}}==
=={{header|Ursala}}==
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import int
#import int


Line 4,437: Line 4,437:
#cast %zL
#cast %zL


t = rex '-6,-3--1,3-5,7-11,14,15,17-20'</lang>
t = rex '-6,-3--1,3-5,7-11,14,15,17-20'</syntaxhighlight>
{{out}}
{{out}}
<pre><-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20></pre>
<pre><-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20></pre>


=={{header|VBA}}==
=={{header|VBA}}==
<lang VBA>Public Function RangeExpand(AString as string)
<syntaxhighlight lang="vba">Public Function RangeExpand(AString as string)
' return a list with the numbers expressed in AString
' return a list with the numbers expressed in AString
Dim Splits() As String
Dim Splits() As String
Line 4,487: Line 4,487:
Next
Next
Debug.Print
Debug.Print
End Sub</lang>
End Sub</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,497: Line 4,497:
=={{header|Wren}}==
=={{header|Wren}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang ecmascript>var expandRange = Fn.new { |s|
<syntaxhighlight lang="ecmascript">var expandRange = Fn.new { |s|
var list = []
var list = []
var items = s.split(",")
var items = s.split(",")
Line 4,525: Line 4,525:


var s = "-6,-3--1,3-5,7-11,14,15,17-20"
var s = "-6,-3--1,3-5,7-11,14,15,17-20"
System.print(expandRange.call(s))</lang>
System.print(expandRange.call(s))</syntaxhighlight>


{{out}}
{{out}}
Line 4,533: Line 4,533:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings, instead of MSb
string 0; \use zero-terminated strings, instead of MSb
char Str;
char Str;
Line 4,574: Line 4,574:
];
];
CrLf(0);
CrLf(0);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 4,582: Line 4,582:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>print RangeExpand$("-6,-3--1,3-5,7-11,14,15,17-20")
<syntaxhighlight lang="yabasic">print RangeExpand$("-6,-3--1,3-5,7-11,14,15,17-20")


sub RangeExpand$(s$)
sub RangeExpand$(s$)
Line 4,604: Line 4,604:
return left$(r$, len(r$) - 1)
return left$(r$, len(r$) - 1)
end sub
end sub
</syntaxhighlight>
</lang>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn rangex(s){
<syntaxhighlight lang="zkl">fcn rangex(s){
fcn(s,re){
fcn(s,re){
if (re.search(s)){
if (re.search(s)){
Line 4,617: Line 4,617:
s.split(",").pump(List, _.fp1(RegExp(0'|(.*\d+)-(.*\d+)|)))
s.split(",").pump(List, _.fp1(RegExp(0'|(.*\d+)-(.*\d+)|)))
.flatten().concat(",");
.flatten().concat(",");
}</lang>
}</syntaxhighlight>
<lang zkl>ns="-6,-3-1,3-5,7-11,14,15,17-20";
<syntaxhighlight lang="zkl">ns="-6,-3-1,3-5,7-11,14,15,17-20";
rangex(ns).println();
rangex(ns).println();


ns="-6,-3--1,3-5,7-11,14,15,17-20";
ns="-6,-3--1,3-5,7-11,14,15,17-20";
rangex(ns).println();</lang>
rangex(ns).println();</syntaxhighlight>


{{out}}
{{out}}