Flatten a list: Difference between revisions
Add Refal
(adding lambdatalk) |
Not a robot (talk | contribs) (Add Refal) |
||
(37 intermediate revisions by 19 users not shown) | |||
Line 14:
=={{header|8th}}==
<
\ take a list (array) and flatten it:
Line 38:
. cr
bye
</syntaxhighlight>
{{out}}
[[1],2,[[3,4],5],[[[]]],[[[6]]],7,8,[]]<br>
Line 44:
=={{header|ACL2}}==
<
(cond ((null tr) nil)
((atom tr) (list tr))
(t (append (flatten (first tr))
(flatten (rest tr))))))</
=={{header|ActionScript}}==
<
var output:Array = new Array();
for (var i:uint = 0; i < input.length; i++) {
Line 64:
return output;
}
</syntaxhighlight>
=={{header|Ada}}==
nestable_lists.ads:
<
type Element_Type is private;
with function To_String (E : Element_Type) return String is <>;
Line 99:
function To_String (L : List) return String;
end Nestable_Lists;</
nestable_lists.adb:
<
package body Nestable_Lists is
Line 179:
end To_String;
end Nestable_Lists;</
example usage:
<
with Nestable_Lists;
Line 209:
Ada.Text_IO.Put_Line (Int_List.To_String (Flattened));
end;
end Flatten_A_List;</
Output:
<pre>[[ 1], 2, [[ 3, 4], 5], [[[]]], [[[ 6]]], 7, 8, []]
Line 215:
=={{header|Aikido}}==
<
function flatten (list, result) {
foreach item list {
Line 239:
println("]")
</syntaxhighlight>
{{out}}
<pre>
Line 246:
=={{header|Aime}}==
<
show_list(list l)
{
Line 294:
return 0;
}</
{{out}}
<pre>
Line 310:
Flattening is built in to all of Algol68's ''transput'' routines. The following example also uses ''widening'', where scalars are converted into arrays.
<
[][][]INT list = ((1), 2, ((3,4), 5), ((())), (((6))), 7, 8, ());
print((list, new line))
)</
{{out}}
<pre>
+1 +2 +3 +4 +5 +6 +7 +8
</pre>
=={{header|APL}}==
=== Dyalog APL ===
Flatten is a primitive in APL, named enlist
<syntaxhighlight lang="apl">∊</syntaxhighlight>
{{out}}
<pre> ∊((1) 2 ((3 4) 5) (((⍬))) (((6))) 7 8 (⍬))
1 2 3 4 5 6 7 8</pre>
=={{header|AppleScript}}==
<
on my_flatten(aList)
Line 331 ⟶ 341:
end if
end my_flatten
</syntaxhighlight>
Or, to make more productive use of the language (where "efficiency" is a function of the scripter's time, rather than the machine's) we can express this in terms of a generic '''concatMap''':
{{trans|JavaScript}}
<
on flatten(t)
if class of t is list then
Line 378 ⟶ 388:
end script
end if
end mReturn</
{{Out}}
<
It can be more efficient to build just one list by appending items to it than to proliferate lists using concatenation:
<
script o
property flatList : {}
Line 410 ⟶ 420:
return o's flatList
end flatten</
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">print flatten [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]</syntaxhighlight>
{{out}}
<pre>1 2 3 4 5 6 7 8</pre>
=={{header|AutoHotkey}}==
Line 417 ⟶ 435:
AutoHotkey doesn't have built in list data type.
This examples simulates a list in a tree type object and flattens that tree.
<
, 2, 5), 4, object(1, object(1, object(1, object()))), 5
, object(1, object(1, 6)), 6, 7, 7, 8, 9, object())
Line 468 ⟶ 486:
}
return flat
}</
=={{header|
==={{header|BaCon}}===
BaCon has the concept of delimited strings, which may contain delimited strings within delimited strings etc. Such nested delimited strings must be surrounded by (escaped) double quotes in order to avoid their delimiter messing up operations on higher level delimited strings. However, from functional point of view, a delimited string is the same as a regular list. The special function FLATTEN$ can actually flatten out lists within lists. The last SORT$ in the program below makes sure no empty items remain in the list.
<
lst$ = "\"1\",2,\"\\\"3,4\\\",5\",\"\\\"\\\\\"\\\\\"\\\"\",\"\\\"\\\\\"6\\\\\"\\\"\",7,8,\"\""
Line 482 ⟶ 501:
UNTIL AMOUNT(lst$, ",") = AMOUNT(FLATTEN$(lst$), ",")
PRINT SORT$(lst$, ",")</
{{out}}
<pre>"1",2,"\"3,4\",5","\"\\"\\"\"","\"\\"6\\"\"",7,8,""
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<
sString = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"
Line 503 ⟶ 519:
Print "["; sFlatter; "]"
End</
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">10 cls
20 sstring$ = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"
30 for sicount = 1 to len(sstring$)
40 if instr("[] ,",mid$(sstring$,sicount,1)) = 0 then
50 sflatter$ = sflatter$+scomma$+mid$(sstring$,sicount,1)
60 scomma$ = ", "
70 endif
80 next sicount
90 print "[";sflatter$;"]"
100 end</syntaxhighlight>
==={{header|FreeBASIC}}===
{{trans|Gambas}}
<syntaxhighlight lang="freebasic">Dim As String sComma, sString, sFlatter
Dim As Short siCount
sString = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"
For siCount = 1 To Len(sString)
If Instr("[] ,", Mid(sString, siCount, 1)) = 0 Then
sFlatter += sComma + Mid(sString, siCount, 1)
sComma = ", "
End If
Next siCount
Print "["; sFlatter; "]"
Sleep</syntaxhighlight>
{{out}}
<pre>[1, 2, 3, 4, 5, 6, 7, 8]</pre>
==={{header|FutureBasic}}===
Definitely old school.
<syntaxhighlight lang="futurebasic">
local fn FlattenList( list as Str255 ) as Str255
long i
Str255 flatStr, commaStr
flatStr = ""
for i = 1 to len$(list)
if ( instr$( 0, "[] ,", mid$( list, i, 1 ) ) === 0 )
flatStr += commaStr + mid$( list, i, 1 )
commaStr = ", "
end if
next
end fn = flatStr
window 1, @"Flatten a list", ( 0, 0, 350, 150 )
print "["; fn FlattenList( "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]" ); "]"
HandleEvents</syntaxhighlight>
{{output}}
<pre>[1, 2, 3, 4, 5, 6, 7, 8]</pre>
Modern and a little outside the box.
<syntaxhighlight lang="futurebasic">
void local fn FlattenAList
CFStringRef listStr = @"[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]"
CFArrayRef listArr = fn StringComponentsSeparatedByCharactersInSet( listStr, fn CharacterSetWithCharactersInString( @"\"[ ]," ) )
CFMutableArrayRef mutArr = fn MutableArrayWithArray( listArr )
MutableArrayRemoveObject( mutArr, @"" )
CFStringRef flatStr = fn ArrayComponentsJoinedByString( mutArr, @", " )
printf @"[%@]", flatStr
end fn
fn FlattenAList
HandleEvents
</syntaxhighlight>
{{output}}
<pre>[1, 2, 3, 4, 5, 6, 7, 8]</pre>
==={{header|Gambas}}===
'''[https://gambas-playground.proko.eu/?gist=1c0157ce2b7eab99ba4e784e183ba474 Click this link to run this code]'''
<syntaxhighlight lang="gambas">'Code 'borrowed' from Run BASIC
Public Sub Main()
Dim sComma, sString, sFlatter As String
Dim siCount As Short
sString = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"
For siCount = 1 To Len(sString)
If InStr("[] ,", Mid$(sString, siCount, 1)) = 0 Then
sFlatter = sFlatter & sComma & Mid(sString, siCount, 1)
sComma = ","
End If
Next
Print "["; sFlatter; "]"
End</syntaxhighlight>
Output:
<pre>[1,2,3,4,5,6,7,8]</pre>
==={{header|GW-BASIC}}===
{{works with|Chipmunk Basic}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">10 CLS
20 SSTRING$ = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"
30 FOR SICOUNT = 1 TO LEN(SSTRING$)
40 IF INSTR("[] ,",MID$(SSTRING$,SICOUNT,1)) = 0 THEN SFLATTER$ = SFLATTER$+SCOMMA$+MID$(SSTRING$,SICOUNT,1): SCOMMA$ = ", "
50 NEXT SICOUNT
60 PRINT "[";SFLATTER$;"]"
70 END</syntaxhighlight>
==={{header|MSX Basic}}===
{{works with|QBasic}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
<syntaxhighlight lang="qbasic">10 CLS
20 S$ = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"
30 FOR SICOUNT = 1 TO LEN(S$)
40 IF INSTR("[] ,",MID$(S$,SICOUNT,1)) = 0 THEN SFLATTER$ = SFLATTER$+SCOMMA$+MID$(S$,SICOUNT,1): SCOMMA$ = ", "
50 NEXT SICOUNT
60 PRINT "[";SFLATTER$;"]"
70 END</syntaxhighlight>
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">Structure RCList
Value.i
List A.RCList()
EndStructure
Procedure Flatten(List A.RCList())
ResetList(A())
While NextElement(A())
With A()
If \Value
Continue
Else
ResetList(\A())
While NextElement(\A())
If \A()\Value: A()\Value=\A()\Value: EndIf
Wend
EndIf
While ListSize(\A()): DeleteElement(\A()): Wend
If Not \Value: DeleteElement(A()): EndIf
EndWith
Wend
EndProcedure</syntaxhighlight>
Set up the MD-List & test the Flattening procedure.
<syntaxhighlight lang="purebasic">;- Set up two lists, one multi dimensional and one 1-D.
NewList A.RCList()
;- Create a deep list
With A()
AddElement(A()): AddElement(\A()): AddElement(\A()): \A()\Value=1
AddElement(A()): A()\Value=2
AddElement(A()): AddElement(\A()): \A()\Value=3
AddElement(\A()): \A()\Value=4
AddElement(A()): AddElement(\A()): \A()\Value=5
AddElement(A()): AddElement(\A()): AddElement(\A()): AddElement(\A())
AddElement(A()): AddElement(\A()): AddElement(\A()): \A()\Value=6
AddElement(A()): A()\Value=7
AddElement(A()): A()\Value=8
AddElement(A()): AddElement(\A()): AddElement(\A())
EndWith
Flatten(A())
;- Present the result
If OpenConsole()
Print("Flatten: [")
ForEach A()
Print(Str(A()\Value))
If ListIndex(A())<(ListSize(A())-1)
Print(", ")
Else
PrintN("]")
EndIf
Next
Print(#CRLF$+"Press ENTER to quit"): Input()
EndIf</syntaxhighlight><pre>Flatten: [1, 2, 4, 5, 6, 7, 8]</pre>
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">sString$ = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"
FOR siCount = 1 TO LEN(sString$)
IF INSTR("[] ,", MID$(sString$, siCount, 1)) = 0 THEN
sFlatter$ = sFlatter$ + sComma$ + MID$(sString$, siCount, 1)
sComma$ = ", "
END IF
NEXT siCount
PRINT "["; sFlatter$; "]"
END</syntaxhighlight>
==={{header|Run BASIC}}===
{{incorrect|Run BASIC| The task is not in string translation but in list translation.}}
<syntaxhighlight lang="runbasic">n$ = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"
for i = 1 to len(n$)
if instr("[] ,",mid$(n$,i,1)) = 0 then
flatten$ = flatten$ + c$ + mid$(n$,i,1)
c$ = ","
end if
next i
print "[";flatten$;"]"</syntaxhighlight>
{{out}}
<pre>[1,2,3,4,5,6,7,8]</pre>
==={{header|TI-89 BASIC}}===
There is no nesting of lists or other data structures in TI-89 BASIC, short of using variable names as pointers.
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">LET sstring$ = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"
FOR sicount = 1 TO LEN(sstring$)
IF pos("[] ,",(sstring$)[sicount:sicount+1-1]) = 0 THEN
LET sflatter$ = sflatter$ & scomma$ & (sstring$)[sicount:sicount+1-1]
LET scomma$ = ", "
END IF
NEXT sicount
PRINT "["; sflatter$; "]"
END</syntaxhighlight>
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">PROGRAM "Flatten a list"
DECLARE FUNCTION Entry ()
FUNCTION Entry ()
n$ = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"
FOR i = 1 TO LEN(n$)
IF INSTR("[] ,",MID$(n$,i,1)) = 0 THEN
flatten$ = flatten$ + c$ + MID$(n$,i,1)
c$ = ", "
END IF
NEXT i
PRINT "[";flatten$;"]"
END FUNCTION
END PROGRAM</syntaxhighlight>
{{out}}
<pre>[1, 2, 3, 4, 5, 6, 7, 8]</pre>
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="yabasic">sString$ = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"
For siCount = 1 To Len(sString$)
If Instr("[] ,", Mid$(sString$, siCount, 1)) = 0 Then
sFlatter$ = sFlatter$ + sComma$ + Mid$(sString$, siCount, 1)
sComma$ = ", "
End If
Next siCount
Print "[", sFlatter$, "]"
End</syntaxhighlight>
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
==={{header|ZX Spectrum Basic}}===
{{incorrect|ZX Spectrum Basic| The task is not in string translation but in list translation.}}
<syntaxhighlight lang="zxbasic">10 LET f$="["
20 LET n$="[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"
30 FOR i=2 TO (LEN n$)-1
40 IF n$(i)>"/" AND n$(i)<":" THEN LET f$=f$+n$(i): GO TO 60
50 IF n$(i)="," AND f$(LEN f$)<>"," THEN LET f$=f$+","
60 NEXT i
70 LET f$=f$+"]": PRINT f$</syntaxhighlight>
=={{header|BQN}}==
<syntaxhighlight lang="bqn">Enlist ← {(∾𝕊¨)⍟(1<≡)⥊𝕩}</syntaxhighlight>
{{out}}
<pre>
Enlist ⟨⟨1⟩, 2, ⟨⟨3, 4⟩, 5⟩, ⟨⟨⟨⟩⟩⟩, ⟨⟨⟨6⟩⟩⟩, 7, 8, ⟨⟩⟩
⟨ 1 2 3 4 5 6 7 8 ⟩
</pre>
=={{header|Bracmat}}==
Line 519 ⟶ 806:
A list that should not be flattened upon evaluation can be separated with dots.
<
( (myList = ((1), 2, ((3,4), 5), ((())), (((6))), 7, 8, ()))
& put$("Unevaluated:")
Line 527 ⟶ 814:
& lst$myList
)
</syntaxhighlight>
=={{header|Brat}}==
<
true? my.empty?
{ [] }
Line 541 ⟶ 828:
list = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
p "List: #{list}"
p "Flattened: #{list.flatten}"</
=={{header|Burlesque}}==
Line 548 ⟶ 835:
until the Block does not contain Blocks anymore.
<
blsq ) {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}{\[}{)to{"Block"==}ay}w!
{1 2 3 4 5 6 7 8}
</syntaxhighlight>
=={{header|C}}==
<
#include <stdlib.h>
#include <string.h>
Line 671 ⟶ 958:
/* delete_list(l); delete_list(flat); */
return 0;
}</
{{out}}
<pre>Nested: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Line 681 ⟶ 968:
Actual Workhorse code
<
using System;
using System.Collections;
Line 708 ⟶ 995:
}
}
</syntaxhighlight>
Method showing population of arraylist and usage of flatten method
<
using System;
using System.Collections;
Line 753 ⟶ 1,040:
}
</syntaxhighlight>
{{works with|C sharp|C#|4+}}
<
public static class Ex {
public static List<object> Flatten(this List<object> list) {
Line 785 ⟶ 1,072:
}
}
</syntaxhighlight>
=={{header|C++}}==
<
#include <boost/any.hpp>
Line 810 ⟶ 1,097:
++current;
}
}</
Use example:
Line 818 ⟶ 1,105:
Also, there's no standard way to output this type of list,
so some output code is added as well.
<
#include <iostream>
Line 921 ⟶ 1,208:
print_list(list);
std::cout << "\n";
}</
{{out}}
<pre>
Line 929 ⟶ 1,216:
=={{header|Ceylon}}==
<
"Lazily flatten nested streams"
{Anything*} flatten({Anything*} stream)
Line 941 ⟶ 1,228:
print(list);
print(flatten(list).sequence());
}</
{{out}}
<pre>
Line 950 ⟶ 1,237:
=={{header|Clojure}}==
The following returns a lazy sequence of the flattened data structure.
<
(lazy-seq
(when-let [s (seq coll)]
(if (coll? (first s))
(concat (flatten (first s)) (flatten (rest s)))
(cons (first s) (flatten (rest s)))))))</
The built-in flatten is implemented as:
<
(filter (complement sequential?)
(rest (tree-seq sequential? seq x))))</
=={{header|CoffeeScript}}==
<
flatten = (arr) ->
arr.reduce ((xs, el) ->
Line 975 ⟶ 1,262:
list = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
console.log flatten list
</syntaxhighlight>
Ouput:
<syntaxhighlight lang="text">
> coffee foo.coffee
[ 1, 2, 3, 4, 5, 6, 7, 8 ]
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(cond ((null structure) nil)
((atom structure) (list structure))
(t (mapcan #'flatten structure))))</
or, from Paul Graham's OnLisp,
<
(defun flatten (ls)
(labels ((mklist (x) (if (listp x) x (list x))))
(mapcan #'(lambda (x) (if (atom x) (mklist x) (flatten x))) ls)))
</syntaxhighlight>
Note that since, in Common Lisp, the empty list, boolean false and <code>nil</code> are the same thing, a tree of <code>nil</code> values cannot be flattened; they will disappear.
A third version that is recursive, imperative, and reasonably fast.
<
(let (result)
(labels ((grep (obj)
Line 1,007 ⟶ 1,294:
(grep (first obj))))))
(grep obj)
result)))</
The following version is tail recursive and functional.
<
(cond ((consp x) (flatten (rest x) (cons (first x) stack) out))
(x (flatten (first stack) (rest stack) (cons x out)))
(stack (flatten (first stack) (rest stack) out))
(t out)))</
The next version is imperative, iterative and does not make use of a stack. It is faster than the versions given above.
<
(do* ((result (list obj))
(node result))
Line 1,024 ⟶ 1,311:
(when (cdar node) (push (cdar node) (cdr node)))
(setf (car node) (caar node)))
(t (setf node (cdr node))))))</
The above implementations of flatten give the same output on nested proper lists.
{{Out}}
Line 1,051 ⟶ 1,338:
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">
[[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()
</syntaxhighlight>
<syntaxhighlight lang="bash">
[1, 2, 3, 4, 5, 6, 7, 8]
</syntaxhighlight>
=={{header|D}}==
Instead of a Java-like class-based version, this version minimizes heap activity using a tagged union.
<
struct TreeList(T) {
Line 1,102 ⟶ 1,389:
l.writeln;
l.flatten.writeln;
}</
{{out}}
<pre>[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Line 1,108 ⟶ 1,395:
===With an Algebraic Data Type===
A shorter and more cryptic version.
<
alias T = Algebraic!(int, This[]);
Line 1,126 ⟶ 1,413:
T( T[].init )
]).flatten.writeln;
}</
{{out}}
[1, 2, 3, 4, 5, 6, 7, 8]
=={{header|Déjà Vu}}==
<
for i in copy:
i
Line 1,141 ⟶ 1,428:
!. flatten [ [ 1 ] 2 [ [ 3 4 ] 5 ] [ [ [] ] ] [ [ [ 6 ] ] ] 7 8 [] ]</
{{out}}
<pre>[ 1 2 3 4 5 6 7 8 ]</pre>
Line 1,147 ⟶ 1,434:
=={{header|E}}==
<
def flat := [].diverge()
def recur(x) {
Line 1,157 ⟶ 1,444:
recur(nested)
return flat.snapshot()
}</
<
# value: [1, 2, 3, 4, 5, 6, 7, 8]</
=={{header|EchoLisp}}==
The built-in '''(flatten list)''' is defined as follows:
<
(define (fflatten l)
(cond
Line 1,192 ⟶ 1,479:
→ ((4) (5 5 5) (6 6) (7) (8) (7 7 7) (9))
</syntaxhighlight>
=={{header|Ela}}==
Line 1,198 ⟶ 1,485:
This implementation can flattern any given list:
<
flat = flat' []
Line 1,206 ⟶ 1,493:
| else = x :: flat' n xs
flat xs</
{{out}}
Line 1,213 ⟶ 1,500:
An alternative solution:
<
flat (x::xs)
| x is List = flat x ++ flat xs
| else = x :: flat xs</
=={{header|Elixir}}==
<
defmodule RC do
def flatten([]), do: []
Line 1,232 ⟶ 1,519:
# Library function
IO.inspect List.flatten(list)
</syntaxhighlight>
{{out}}
<pre>
Line 1,241 ⟶ 1,528:
=={{header|Elm}}==
<
import Graphics.Element exposing (show)
Line 1,269 ⟶ 1,556:
main =
show (flatten tree)
</syntaxhighlight>
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(defun flatten (mylist)
(cond
((null mylist) nil)
((atom mylist) (list mylist))
(t
(append (flatten (car mylist)) (flatten (cdr mylist))))))</syntaxhighlight>
The flatten-tree function was added in Emacs 27.1 or earlier.
<syntaxhighlight lang="lisp">
(flatten-tree mylist)
</syntaxhighlight>
=={{header|Erlang}}==
There's a standard function (lists:flatten/1) that does it more efficiently, but this is the cleanest implementation you could have;
<
flatten([H|T]) -> flatten(H) ++ flatten(T);
flatten(H) -> [H].</
=={{header|Euphoria}}==
{{works with|Euphoria|4.0.0}}
<
function flatten( object s )
Line 1,309 ⟶ 1,600:
? a
? flatten(a)</
{{out}}
<pre>{
Line 1,334 ⟶ 1,625:
=={{header|F_Sharp|F#}}==
As with Haskell and OCaml we have to define our list as an algebraic data type, to be strongly typed:
<
| I of 'a // leaf Item
| L of 'a ll list // ' <- confine the syntax colouring confusion
Line 1,345 ⟶ 1,636:
printfn "%A" (flatten [L([I(1)]); I(2); L([L([I(3);I(4)]); I(5)]); L([L([L([])])]); L([L([L([I(6)])])]); I(7); I(8); L([])])
// -> [1; 2; 3; 4; 5; 6; 7; 8]</
An alternative approach with List.collect
and the same data type. Note that flatten operates on all deepLists (ll) and atoms (I) are "flatened" to lists.
<
let rec flatten =
function
Line 1,359 ⟶ 1,650:
// -> [1; 2; 3; 4; 5; 6; 7; 8]
</syntaxhighlight>
=={{header|Factor}}==
Line 1,368 ⟶ 1,659:
=={{header|Fantom}}==
<
class Main
{
Line 1,394 ⟶ 1,685:
}
}
</syntaxhighlight>
=={{header|Forth}}==
Line 1,401 ⟶ 1,692:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
<
include FMS-SILib.f
Line 1,412 ⟶ 1,703:
o{ o{ 1 } 2 o{ o{ 3 4 } 5 } o{ o{ o{ } } } o{ o{ o{ 6 } } } 7 8 o{ } }
list flatten
list p: \ o{ 1 2 3 4 5 6 7 8 } ok</
=={{header|Fortran}}==
<
! input : [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
! flatten : [1, 2, 3, 4, 5, 6, 7, 8 ]
Line 1,567 ⟶ 1,858:
print *, "]"
end program
</syntaxhighlight>
===Or, older style===
Fortran does not offer strings, only CHARACTER variables of some fixed size. Functions can return such types, but, must specify a fixed size. Or, mess about with run-time allocation as above. Since in principle a list is arbitrarily long, the plan here is to crush its content in place, and thereby never have to worry about long-enough work areas. This works because the transformations in mind never replace something by something longer. A subroutine can receive an arbitrary-sized CHARACTER variable, and can change it. No attempt is made to detect improper lists.
<syntaxhighlight lang="fortran">
SUBROUTINE CRUSH(LIST) !Changes LIST.
Crushes a list holding multi-level entries within [...] to a list of single-level entries. Null entries are purged.
Line 1,604 ⟶ 1,895:
CALL CRUSH(STUFF) !Can't be a constant, as it will be changed.
WRITE (6,*) " Crushed: ",STUFF !Behold!
END</
Output is
Original: [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
Line 1,611 ⟶ 1,902:
All of this relies on the list being presented as a flat text, which text is then manipulated directly. If the list was manifested in a data structure of some kind with links and suchlike, then tree-traversal of that structure would be needed to reach the leaf entries.
=={{header|Frink}}==
<
a = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
println[flatten[a]]
</syntaxhighlight>
=={{header|GAP}}==
<
=={{header|GNU APL}}==
Using (monadic) enlist function ε. Sometimes called 'Super Ravel'.
<syntaxhighlight lang="apl">
⊢list←(2 3ρι6)(2 2ρ(7 8(2 2ρ9 10 11 12)13)) 'ABCD'
┏→━━━━━━━━━━━━━━━━━━━━━━━━━━┓
Line 1,685 ⟶ 1,930:
┃1 2 3 4 5 6 7 8 9 10 11 12 13 'A''B''C''D'┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
</syntaxhighlight>
=={{header|Go}}==
<
import "fmt"
Line 1,720 ⟶ 1,965:
}
return
}</
{{out}}
<pre>
Line 1,728 ⟶ 1,973:
In the code above, flatten uses an easy-to-read type switch to extract ints and return an int slice. The version below is generalized to return a flattened slice of interface{} type, which can of course refer to objects of any type, and not just int.
Also, just to show a variation in programming style, a type assertion is used rather than a type switch.
<
for _, e := range s {
if i, ok := e.([]interface{}); ok {
Line 1,737 ⟶ 1,982:
}
return
}</
=={{header|Groovy}}==
Line 1,743 ⟶ 1,988:
<code>List.flatten()</code> is a Groovy built-in that returns a flattened copy of the source list:
<
=={{header|Haskell}}==
Line 1,749 ⟶ 1,994:
In Haskell we have to interpret this structure as an algebraic data type.
<
-- [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
Line 1,774 ⟶ 2,019:
main :: IO ()
main = print $ flattenList list</
{{Out}}
<pre>[1,2,3,4,5,6,7,8]</pre>
Alternately:
<
= Leaf a
| Node [Tree a]
Line 1,801 ⟶ 2,046:
]
-- [1,2,3,4,5,6,7,8]</
Yet another choice, custom data structure, efficient lazy flattening:
Line 1,807 ⟶ 2,052:
(This is unnecessary; since Haskell is lazy, the previous solution will only do just as much work as necessary for each element that is requested from the resulting list.)
<
= NList [NestedList a]
| Entry a
Line 1,835 ⟶ 2,080:
main :: IO ()
main = print $ flatten example
-- output [1,2,3,4,5,6,7,8]</
=={{header|Hy}}==
<
(sum (genexpr (if (isinstance x list)
(flatten x)
Line 1,846 ⟶ 2,091:
(print (flatten [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []]))
; [1, 2, 3, 4, 5, 6, 7, 8]</
=={{header|Icon}} and {{header|Unicon}}==
The following procedure solves the task using a string representation of nested lists and cares not if the list is well formed or not.
<
procedure sflatten(s) # uninteresting string solution
return pretrim(trim(compress(deletec(s,'[ ]'),',') ,','),',')
end</
{{libheader|Icon Programming Library}}
The solution uses several procedures from [http://www.cs.arizona.edu/icon/library/src/procs/strings.icn strings in the IPL]
This procedure is more in the spirit of the task handling actual lists rather than representations. It uses a recursive approach using some of the built-in list manipulation functions and operators.
<
local l,x
Line 1,867 ⟶ 2,112:
else put(l,x)
return l
end</
Finally a demo routine to drive these and a helper to show how it works.
<
write(sflatten(" [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]"))
writelist(flatten( [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]))
Line 1,880 ⟶ 2,125:
write(" ]")
return
end</
=={{header|Insitux}}==
Insitux has a built-in flatten function.
<syntaxhighlight lang="insitux">
(flatten [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []])
</syntaxhighlight>
{{out}}
<pre>
[1 2 3 4 5 6 7 8]
</pre>
=={{header|Ioke}}==
<
[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] flatten
+> [1, 2, 3, 4, 5, 6, 7, 8]</
=={{header|Isabelle}}==
<
imports Main
begin
Line 1,922 ⟶ 2,177:
by(simp add: example_def)
end</
=={{header|J}}==
'''Solution''':
<
'''Example''':
<
]li =. (<1) ; 2; ((<3; 4); 5) ; ((<a:)) ; ((<(<6))) ; 7; 8; <a:
+---+-+-----------+----+-----+-+-+--+
Line 1,943 ⟶ 2,198:
flatten li
1 2 3 4 5 6 7 8</
'''Notes:'''
Line 1,958 ⟶ 2,213:
'''Alternative Solution:'''<br>
The previous solution can be generalized to flatten the nesting and shape for a list of arbitrary values that include arrays of any rank:
<
'''Example:'''
<
+---+-+---------------------+----+------+--+--+--+
|+-+|2|+-------+-----------+|+--+|+----+|18|19|++|
Line 1,975 ⟶ 2,230:
1 2 3 4 5 6 7 8
flatten2 li2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19</
Here, we have replaced <code><S:0</code> with <code><@,S:0</code> so our leaves are flattened before the final step where their boxes are razed.
Line 1,987 ⟶ 2,242:
Actual Workhorse code
<
import java.util.List;
Line 2,008 ⟶ 2,263:
}
}
}</
Method showing population of the test List and usage of flatten method.
<
import java.util.List;
Line 2,026 ⟶ 2,281:
return asList(a);
}
}</
{{out}}
Line 2,034 ⟶ 2,289:
;Functional version
{{works with|Java|8+}}
<
import java.util.stream.Stream;
import java.util.stream.Collectors;
Line 2,050 ⟶ 2,305:
return flattenToStream(list).collect(Collectors.toList());
}
}</
=={{header|JavaScript}}==
===ES5===
<
return list.reduce(function (acc, val) {
return acc.concat(val.constructor === Array ? flatten(val) : val);
}, []);
}</
Or, expressed in terms of the more generic '''concatMap''' function:
<
'use strict';
Line 2,080 ⟶ 2,335:
);
})();</
From fusion of ''flatten'' with ''concatMap'' we can then derive:
<
function flatten(a) {
return a instanceof Array ? [].concat.apply([], a.map(flatten)) : a;
}</
For example:
<
'use strict';
Line 2,104 ⟶ 2,359:
);
})();</
{{Out}}
Line 2,113 ⟶ 2,368:
====Built-in====
<
const flatten = nest =
nest.flat(Infinity);</syntaxhighlight>
====Recursive====
<
const flatten = t => {
const go = x =>
Line 2,124 ⟶ 2,380:
) : x;
return go(t);
};</
====Iterative====
<
for (let i = 0; i < list.length; i++) {
while (true) {
Line 2,138 ⟶ 2,394:
}
return list;
}</
Or alternatively:
<
const flatten = t => {
let xs = t;
while
xs = [].concat(...xs);
}
return xs;
};</
Result is always:
Line 2,155 ⟶ 2,413:
=={{header|Joy}}==
<syntaxhighlight lang="joy">
"seqlib" libload.
Line 2,161 ⟶ 2,419:
(* output: [1 2 3 4 5 6 7 8] *)
</syntaxhighlight>
=={{header|jq}}==
Recent (1.4+) versions of jq include the following flatten filter:<
reduce .[] as $i
([];
if $i | type == "array" then . + ($i | flatten)
else . + [$i]
end);</
[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] | flatten
[1,2,3,4,5,6,7,8]</
=={{header|Jsish}}==
From Javascript entry, with change to test for ''typeof'' equal ''"array"''.
<
function flatten(list) {
return list.reduce(function (acc, val) {
Line 2,191 ⟶ 2,449:
flatten([[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]) ==> [ 1, 2, 3, 4, 5, 6, 7, 8 ]
=!EXPECTEND!=
*/</
{{out}}
Line 2,198 ⟶ 2,456:
=={{header|Julia}}==
(Note that Julia versions prior to 0.5
The following version of flatten makes use of the higher order function ''mapreduce''.
<syntaxhighlight lang="julia">isflat(x) = isempty(x) || first(x) === x
function flat_mapreduce(arr)
mapreduce(vcat, arr, init=[]) do x
isflat(x) ? x : flat(x)
end
end</syntaxhighlight>
An iterative recursive version that uses less memory but is slower:
<
function grep(v)
if x isa Array
grep(x)
else
push!(res, x)
end
end
end
grep(arr)
end</syntaxhighlight>
Using the Iterators library from the Julia base:
<syntaxhighlight lang="julia">function flat_iterators(arr)
while any(a -> a isa Array, arr)
end
arr
end</syntaxhighlight>
Benchmarking these three functions using the BenchmarkTools package yields the following results:
<syntaxhighlight lang="julia">using BenchmarkTools
arr = [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
@show
@show
@show
@btime
@btime
@btime
<pre>
</pre>
Line 2,240 ⟶ 2,513:
So to flatten a list of arbitrary depth, you can join-over-over, or reduce a list with a function that reduces a list with a join function:
<
=={{header|Kotlin}}==
<
@Suppress("UNCHECKED_CAST")
Line 2,271 ⟶ 2,544:
flattenList(nestList, flatList)
println("Flattened : " + flatList)
}</
Or, using a more functional approach:
<
fun flatten(list: List<*>): List<*> {
fun flattenElement(elem: Any?): Iterable<*> {
Line 2,284 ⟶ 2,557:
}
return list.flatMap { elem -> flattenElement(elem) }
}</
{{out}}
Line 2,294 ⟶ 2,567:
=={{header|Lambdatalk}}==
Lambdatalk doesn't have a builtin primitive flattening a multidimensionnal array.
<
1) Let's create this function
Line 2,328 ⟶ 2,601:
{A.flatten {list}}
-> [1,2,3,4,5,6,7,8]
</syntaxhighlight>
=={{header|Lasso}}==
Lasso Delve is a Lasso utility method explicitly for handling embedded arrays. With one array which contain other arrays, delve allows you to treat one array as a single series of elements, thus enabling easy access to an entire tree of values. [http://www.lassosoft.com/lassoDocs/languageReference/obj/delve www.lassosoft.com/lassoDocs/languageReference/obj/delve Lasso reference on Delve]
<
#original
'<br />'
(with item in delve(#original)
select #item) -> asstaticarray</
<pre>array(array(1), 2, array(array(3, 4), 5), array(array(array())), array(array(array(6))), 7, 8, array())
staticarray(1, 2, 3, 4, 5, 6, 7, 8)</pre>
=={{header|LFE}}==
<
> (: lists flatten '((1) 2 ((3 4) 5) ((())) (((6))) 7 8 ()))
(1 2 3 4 5 6 7 8)
</syntaxhighlight>
=={{header|Logo}}==
<
if not list? :l [output :l]
if empty? :l [output []]
Line 2,361 ⟶ 2,634:
make "a [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []]
show flatten :a</
=={{header|Logtalk}}==
<
flatten(List, [], Flatted).
Line 2,376 ⟶ 2,649:
flatten(Tail, List, Aux),
flatten(Head, Aux, Flatted).
flatten(Head, Tail, [Head| Tail]).</
=={{header|Lua}}==
<
if type(list) ~= "table" then return {list} end
local flat_list = {}
Line 2,393 ⟶ 2,666:
test_list = {{1}, 2, {{3,4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}}
print(table.concat(flatten(test_list), ","))</
=={{header|Maple}}==
Line 2,399 ⟶ 2,672:
This can be accomplished using the <code>Flatten</code> command from the <code>ListTools</code>, or with a custom recursive procedure.
<syntaxhighlight lang="maple">
L := [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]:
Line 2,405 ⟶ 2,678:
Flatten(L);
</syntaxhighlight>
{{out}}
<pre>
Line 2,411 ⟶ 2,684:
</pre>
<syntaxhighlight lang="maple">
flatten := proc(x)
`if`(type(x,'list'),seq(procname(i),i = x),x);
Line 2,419 ⟶ 2,692:
[flatten(L)];
</syntaxhighlight>
{{out}}
<pre>
Line 2,426 ⟶ 2,699:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
=={{header|Maxima}}==
<
/* [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] */</
=={{header|Mercury}}==
As with Haskell we need to use an algebraic data type.
<
:- interface.
Line 2,468 ⟶ 2,741:
:- end_module flatten_a_list.
</syntaxhighlight>
{{out}}
<pre>
Line 2,475 ⟶ 2,748:
=={{header|min}}==
{{works with|min|0.
<
(dup 'quotation? any?) 'flatten while
) ^deep-flatten
((1) 2 ((3 4) 5) ((())) (((6))) 7 8 ()) deep-flatten puts!</
{{out}}
<pre>(1 2 3 4 5 6 7 8)</pre>
=={{header|Mirah}}==
<
import java.util.List
import java.util.Collection
Line 2,512 ⟶ 2,781:
source = [[1], 2, [[3, 4], 5], [[ArrayList.new]], [[[6]]], 7, 8, ArrayList.new]
puts flatten(source)</
=={{header|NewLISP}}==
<
(1 2 3 4 5 6 7 8)
</syntaxhighlight>
=={{header|NGS}}==
Line 2,524 ⟶ 2,793:
NGS defines '''flatten''' as a shallow flatten, hence using '''flatten_r''' here.
<
collector {
local kern
Line 2,532 ⟶ 2,801:
}
echo(flatten_r([[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]))</
{{out}}
Line 2,538 ⟶ 2,807:
=={{header|Nim}}==
Nim is statically-typed, so we need to use an object variant
<syntaxhighlight lang="nim">type
case isLeaf: bool
of true:
of false: list: seq[TreeList[T]]
proc L[T](list: varargs[TreeList[T]]): TreeList[T] =
for x in list:
proc N[T](data: T): TreeList[T] =
TreeList[T](isLeaf: true, data: data)
proc flatten[T](n: TreeList[T]): seq[T] =
if n.isLeaf: result = @[n.data]
else:
for x in n.list:
result.add flatten x
var x = L(L(N 1), N 2, L(L(N 3, N 4), N 5), L(L(L[int]())), L(L(L(N 6))), N 7, N 8, L[int]())
echo flatten(x)</syntaxhighlight>
{{out}}
<pre>
=={{header|Objective-C}}==
{{works with|Cocoa}}
<
@interface NSArray (FlattenExt)
Line 2,617 ⟶ 2,873:
return 0;
}</
=={{header|OCaml}}==
<
val flatten : 'a list list -> 'a list = <fun>
Line 2,629 ⟶ 2,885:
# (* use another data which can be accepted by the type system *)
flatten [[1]; [2; 3; 4]; []; [5; 6]; [7]; [8]] ;;
- : int list = [1; 2; 3; 4; 5; 6; 7; 8]</
Since OCaml is statically typed, it is not possible to have a value that could be both a list and a non-list. Instead, we can use an algebraic datatype:
<
type 'a tree = Leaf of 'a | Node of 'a tree list
Line 2,642 ⟶ 2,898:
# flatten (Node [Node [Leaf 1]; Leaf 2; Node [Node [Leaf 3; Leaf 4]; Leaf 5]; Node [Node [Node []]]; Node [Node [Node [Leaf 6]]]; Leaf 7; Leaf 8; Node []]) ;;
- : int list = [1; 2; 3; 4; 5; 6; 7; 8]</
=={{header|Oforth}}==
<
{{out}}
Line 2,654 ⟶ 2,910:
=={{header|Ol}}==
<
(define (flatten x)
(cond
Line 2,667 ⟶ 2,923:
(print
(flatten '((1) 2 ((3 4) 5) ((())) (((6))) 7 8 ())))
</syntaxhighlight>
{{Out}}
<pre>
Line 2,674 ⟶ 2,930:
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
sub1 = .array~of(1)
sub2 = .array~of(3, 4)
Line 2,711 ⟶ 2,967:
else accumulator~append(item)
end
</syntaxhighlight>
=={{header|Oz}}==
Oz has a standard library function "Flatten":
<
A simple, non-optimized implementation could look like this:
<
case Xs of nil then nil
[] X|Xr then
Line 2,724 ⟶ 2,980:
end
end
</syntaxhighlight>
=={{header|PARI/GP}}==
<
my(u=[]);
for(i=1,#v,
Line 2,733 ⟶ 2,989:
);
u
};</
=={{header|Perl}}==
<
map { ref eq 'ARRAY' ? flatten(@$_) : $_ } @_
}
my @lst = ([1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []);
print flatten(@lst), "\n";</
=={{header|Phix}}==
standard builtin
<
{{out}}
<pre>
Line 2,752 ⟶ 3,008:
=={{header|Phixmonti}}==
<
dup print nl flatten print</
With syntactic sugar
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt
( 1 2 3 ( ( 10 20 30 ) ( 4 5 6 ) ) 1000 "Hola" )
dup ? flatten ?</syntaxhighlight>
{{out}}
<pre>
Line 2,762 ⟶ 3,026:
=={{header|PHP}}==
{{works with|PHP|4.x only, not 5.x}}
<
It won't work on PHP 5 due to the change in behavior of array_merge(). */
while (array_filter($lst, 'is_array'))
$lst = call_user_func_array('array_merge', $lst);</
Explanation: while <code>$lst</code> has any elements which are themselves arrays (i.e. <code>$lst</code> is not flat), we merge the elements all together (in PHP 4, <code>array_merge()</code> treated non-array arguments as if they were 1-element arrays; PHP 5 <code>array_merge()</code> no longer allows non-array arguments.), thus flattening the top level of any embedded arrays. Repeat this process until the array is flat.
===Recursive===
<
function flatten($ary) {
$result = array();
Line 2,785 ⟶ 3,049:
$lst = array(array(1), 2, array(array(3, 4), 5), array(array(array())), array(array(array(6))), 7, 8, array());
var_dump(flatten($lst));
?></
Alternatively:{{works with|PHP|5.3+}}
<
function flatten($ary) {
$result = array();
Line 2,798 ⟶ 3,062:
$lst = array(array(1), 2, array(array(3, 4), 5), array(array(array())), array(array(array(6))), 7, 8, array());
var_dump(flatten($lst));
?></
<
function flatten_helper($x, $k, $obj) {
$obj->flattened[] = $x;
Line 2,813 ⟶ 3,077:
$lst = array(array(1), 2, array(array(3, 4), 5), array(array(array())), array(array(array(6))), 7, 8, array());
var_dump(flatten($lst));
?></
Using the standard library (warning: objects will also be flattened by this method):
<
$lst = array(array(1), 2, array(array(3, 4), 5), array(array(array())), array(array(array(6))), 7, 8, array());
$result = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($lst)), false);
var_dump($result);
?></
===Non-recursive===
Function flat is iterative and flattens the array in-place.
<
function flat(&$ary) { // argument must be by reference or array will just be copied
for ($i = 0; $i < count($ary); $i++) {
Line 2,838 ⟶ 3,102:
flat($lst);
var_dump($lst);
?></
=={{header|PicoLisp}}==
<
(make # Build a list
(recur (X) # recursively over 'X'
(if (atom X)
(link X) # Put atoms into the result
(mapc recurse X) ) ) ) ) # or recurse on sub-lists</
or a more succint way using [http://www.software-lab.de/doc/refF.html#fish fish]:
<
(fish atom X) )</
=={{header|Pike}}==
There's a built-in function called <code>Array.flatten()</code> which does this, but here's a custom function:
<
array r = ({ });
Line 2,864 ⟶ 3,128:
return r;
}</
=={{header|PL/I}}==
The Translate(text,that,this) intrinsic function returns ''text'' with any character in ''text'' that is found in ''this'' (say the third) replaced by the corresponding third character in ''that''. Suppose the availability of a function Replace(text,that,this) which returns ''text'' with all occurrences of ''this'' (a single text, possibly many characters) replaced by ''that'', possibly zero characters. The Translate function does not change the length of its string, simply translate its characters in place.
<syntaxhighlight lang="pl/i">
list = translate (list, ' ', '[]' ); /*Produces " 1 , 2, 3,4 , 5 , , 6 , 7, 8, " */
list = Replace(list,'',' '); /*Converts spaces to nothing. Same parameter order as Translate.*/
Line 2,875 ⟶ 3,139:
end; /*And search afresh, in case of multiple commas in a row.*/
list = '[' || list || ']'; /*Repackage the list.*/
</syntaxhighlight>
This is distinctly crude. A user-written Replace function is confronted by the requirement to specify a maximum size for its returned result, for instance <code>Replace:Procedure(text,that,this) Returns(Character 200 Varying);</code> which is troublesome for general use. The intrinsic function Translate has no such restriction.
Line 2,882 ⟶ 3,146:
=={{header|PostScript}}==
{{libheader|initlib}}
<
/flatten {
/.f {{type /arraytype eq} {{.f} map aload pop} ift}.
[exch .f]
}.
</syntaxhighlight>
<syntaxhighlight lang="text">
[[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []] flatten
</syntaxhighlight>
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function flatten($a) {
if($a.Count -gt 1) {
Line 2,901 ⟶ 3,165:
$a = @(@(1), 2, @(@(3,4), 5), @(@(@())), @(@(@(6))), 7, 8, @())
"$(flatten $a)"
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 2,908 ⟶ 3,172:
=={{header|Prolog}}==
<syntaxhighlight lang="prolog">
flatten(List, FlatList) :-
flatten(List, [], FlatList).
Line 2,920 ⟶ 3,184:
flatten(NonList, T, [NonList|T]).
</syntaxhighlight>
=={{header|Python}}==
===Recursive===
<syntaxhighlight lang="python">>>> def flatten(lst):
return sum( ([x] if not isinstance(x, list) else flatten(x)
for x in lst), [] )
Line 2,989 ⟶ 3,194:
>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
>>> flatten(lst)
[1, 2, 3, 4, 5, 6, 7, 8]</
===Recursive, generative and working with any type of iterable object===
<syntaxhighlight lang="python">>>> def flatten(itr):
>>> try:
>>>
>>> except:
>>>
>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
>>> list(flatten(lst))
[1, 2, 3, 4, 5, 6, 7, 8]
>>> tuple(flatten(lst))
(1, 2, 3, 4, 5, 6, 7, 8)
>>>for i in flatten(lst):
>>> print(i)
1
2
3
4
5
6
7
8</syntaxhighlight>
===Non-recursive===
Function flat is iterative and flattens the list in-place. It follows the Python idiom of returning None when acting in-place:
<
i=0
while i<len(lst):
Line 3,020 ⟶ 3,238:
>>> flat(lst)
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8]</
===Generative===
Line 3,028 ⟶ 3,246:
In this case, the generator is converted back to a list before printing.
<
for x in lst:
if isinstance(x, list):
Line 3,039 ⟶ 3,257:
>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
>>> print list(flatten(lst))
[1, 2, 3, 4, 5, 6, 7, 8]</
===Functional Recursive===
Line 3,045 ⟶ 3,263:
{{Works with|Python|3.7}}
<
from itertools import (chain)
Line 3,123 ⟶ 3,341:
if __name__ == '__main__':
main()</
{{Out}}
<pre>Flatten a nested list:
Line 3,144 ⟶ 3,362:
{{Works with|Python|3.7}}
<
from functools import (reduce)
Line 3,220 ⟶ 3,438:
if __name__ == '__main__':
main()</
{{Out}}
<pre>From nested list to flattened list:
Line 3,230 ⟶ 3,448:
{{trans|K}}
We repeatedly apply <tt>raze</tt> until the return value converges to a fixed value.
<
=={{header|Quackery}}==
<
[ [] swap
Line 3,239 ⟶ 3,457:
[ dup nest?
if flatten
join ] ] resolves flatten ( [ --> [ )</
'''Output:'''
<
...
Stack: [ 1 2 3 4 5 6 7 8 ]</
=={{header|R}}==
<
unlist(x)</
=={{header|Racket}}==
Racket has a built-in flatten function:
<syntaxhighlight lang="racket">
#lang racket
(flatten '(1 (2 (3 4 5) (6 7)) 8 9))
</syntaxhighlight>
{{out}}
<pre>
Line 3,264 ⟶ 3,482:
or, writing it explicitly with the same result:
<syntaxhighlight lang="racket">
#lang racket
(define (flatten l)
Line 3,271 ⟶ 3,489:
[else (append (flatten (first l)) (flatten (rest l)))]))
(flatten '(1 (2 (3 4 5) (6 7)) 8 9))
</syntaxhighlight>
=={{header|Raku}}==
Line 3,277 ⟶ 3,495:
{{works with|Rakudo Star|2018.03}}
<syntaxhighlight lang="raku"
say .perl given gather @l.deepmap(*.take); # lazy recursive version
Line 3,283 ⟶ 3,501:
# Another way to do it is with a recursive function (here actually a Block calling itself with the &?BLOCK dynamic variable):
say { |(@$_ > 1 ?? map(&?BLOCK, @$_) !! $_) }(@l)</
=={{header|REBOL}}==
<
flatten: func [
"Flatten the block in place."
Line 3,296 ⟶ 3,514:
head block
]
</syntaxhighlight>
Sample: <pre>
Line 3,304 ⟶ 3,522:
=={{header|Red}}==
<syntaxhighlight lang="red">
flatten: function [
"Flatten the block"
Line 3,318 ⟶ 3,536:
>> blk: [1 2 ["test"] "a" [["bb"]] 3 4 [[[99]]]]
>> form blk
== "1 2 test a bb 3 4 99"</
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
, ((1) 2 ((3 4) 5) ((())) (((6))) 7 8 ()): e.List
= <Prout e.List ' -> ' <Flatten e.List>>
};
Flatten {
= ;
s.I e.X = s.I <Flatten e.X>;
(e.X) e.Y = <Flatten e.X> <Flatten e.Y>;
};</syntaxhighlight>
{{out}}
<pre>((1 )2 ((3 4 )5 )((()))(((6 )))7 8 ()) -> 1 2 3 4 5 6 7 8</pre>
=={{header|REXX}}==
{{trans|PL/I}}
<
list= '[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]' /*the list to be flattened. */
say list /*display the original list. */
Line 3,334 ⟶ 3,566:
list= strip(list, 'T', c) /*strip the last trailing comma*/
list = '['list"]" /*repackage the list. */
say list /*display the flattened list. */</
{{out|output|:}}
<pre>
Line 3,342 ⟶ 3,574:
=={{header|Ring}}==
<
aString = "[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]"
bString = ""
Line 3,354 ⟶ 3,586:
cString = '"' + cString + '"'
see cString + nl
</syntaxhighlight>
<pre>
"1, 2, 3, 4, 5, 6, 7, 8"
</pre>
=={{header|RPL}}==
Soberly recursive.
{{works with|Halcyon Calc|4.2.7}}
≪ '''IF''' DUP SIZE '''THEN'''
{ } 1 LAST '''FOR''' j
OVER j GET
'''IF''' DUP TYPE 5 == '''THEN FLATL END'''
+ '''NEXT'''
SWAP DROP '''END'''
≫ ‘'''FLATL'''’ STO
{{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}} '''FLATL'''
{{out}}
<pre>
1: { 1 2 3 4 5 6 7 8 }
</pre>
=={{header|Ruby}}==
<code>flatten</code> is a built-in method of Arrays
<
p flat # => [1, 2, 3, 4, 5, 6, 7, 8]</
The <code>flatten</code> method takes an optional argument, which dedicates the amount of levels to be flattened.
<
# => [1, 2, [3, 4], 5, [[]], [[6]], 7, 8]
</syntaxhighlight>
=={{header|Rust}}==
First we have to create a type that supports arbitrary nesting:
<
enum List<T> {
Line 3,474 ⟶ 3,710:
println!();
}</
{{output}}
<pre>1 2 3 4 5 6 7 8
Line 3,480 ⟶ 3,716:
=={{header|S-lang}}==
<
define flatten (list) {
Line 3,497 ⟶ 3,733:
}
return retval;
}</
Sample:
Line 3,518 ⟶ 3,754:
=={{header|Scala}}==
<
case Nil => Nil
case (head: List[_]) :: tail => flatList(head) ::: flatList(tail)
case head :: tail => head :: flatList(tail)
}</
Sample:
Line 3,535 ⟶ 3,771:
=={{header|Scheme}}==
<
(cond ((null? x) '())
((not (pair? x)) (list x))
Line 3,542 ⟶ 3,778:
> (flatten '((1) 2 ((3 4) 5) ((())) (((6))) 7 8 ()))
(1 2 3 4 5 6 7 8)</
=={{header|Shen}}==
<syntaxhighlight lang="shen">
(define flatten
[] -> []
Line 3,552 ⟶ 3,788:
(flatten [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []])
</syntaxhighlight>
{{out}}
<pre>
Line 3,559 ⟶ 3,795:
=={{header|Sidef}}==
<
var flat = []
a.each { |item|
Line 3,569 ⟶ 3,805:
var arr = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
say flatten(arr) # used-defined function
say arr.flatten # built-in Array method</
=={{header|Slate}}==
<
[
[| :out | s flattenOn: out] writingAs: s
Line 3,583 ⟶ 3,819:
ifTrue: [value flattenOn: w]
ifFalse: [w nextPut: value]].
].</
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<
flatten [ |f|
f := OrderedCollection new.
Line 3,609 ⟶ 3,845:
{{{}}} . {{{6}}} . 7 . 8 . {} }.
(list flatten) printNl.</
Here is a non-OOP (but functional) version, which uses a block-closure as function (showing higher order features of Smalltalk):
<
flatDo :=
[:element :action |
Line 3,631 ⟶ 3,867:
flatDo
value:collection
value:[:el | newColl add: el]</
of course, many Smalltalk libraries already provide such functionality.
{{works with|Smalltalk/X}} {{works with|Pharo}}
<
=={{header|Standard ML}}==
In Standard ML, list must be homogeneous, but nested lists can be implemented as a tree-like data structure using a <code>datatype</code> statement:
<
L of 'a (* leaf *)
| N of 'a nestedList list (* node *)
</syntaxhighlight>
Flattening of this structure is similar to flatten trees:
<
| flatten (N xs) = List.concat (map flatten xs)</
{{out}}
Line 3,654 ⟶ 3,890:
=={{header|Suneido}}==
<
ob.Flatten()</
{{out}}
Line 3,662 ⟶ 3,898:
=={{header|SuperCollider}}==
SuperCollider has the method "flat", which completely flattens nested lists, and the method "flatten(n)" to flatten a certain number of levels.
<syntaxhighlight lang="supercollider">
a = [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []];
a.flatten(1); // answers [ 1, 2, [ 3, 4 ], 5, [ [ ] ], [ [ 6 ] ], 7, 8 ]
a.flat; // answers [ 1, 2, 3, 4, 5, 6, 7, 8 ]
</syntaxhighlight>
Written as a function:
<syntaxhighlight lang="supercollider">
(
f = { |x|
Line 3,683 ⟶ 3,919:
};
f.([[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]);
)</
=={{header|Swift}}==
=== Recursive ===
<syntaxhighlight lang="swift">func list(s: Any...) -> [Any] {
return s
}
Line 3,719 ⟶ 3,953:
println(s)
let result : [Int] = flatten(s)
println(result)</
{{out}}
<pre>
Line 3,728 ⟶ 3,962:
More functionally:
{{works with|Swift|1.2+}}
<
return s
}
Line 3,756 ⟶ 3,990:
println(s)
let result : [Int] = flatten(s)
println(result)</
{{out}}
<pre>
Line 3,763 ⟶ 3,997:
</pre>
=== Non-recursive ==
{{works with|Swift|2.0+}}
<syntaxhighlight lang="swift">func list(s: Any...) -> [Any]
{
return s
Line 3,813 ⟶ 4,045:
let result: [Int] = flatten(input)
print(result)</
{{out}}
<pre>
Line 3,821 ⟶ 4,053:
=={{header|Tailspin}}==
<
templates flatten
[ $ -> # ] !
Line 3,831 ⟶ 4,063:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] -> flatten -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 3,838 ⟶ 4,070:
=={{header|Tcl}}==
<
for {set old {}} {$old ne $list} {} {
set old $list
Line 3,847 ⟶ 4,079:
puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
# ===> 1 2 3 4 5 6 7 8</
Note that because lists are not syntactically distinct from strings, it is probably a mistake to use this procedure with real (especially non-numeric) data. Also note that there are no parentheses around the outside of the list when printed; this is just a feature of how Tcl regards lists, and the value is a proper list (it can be indexed into with <code>lindex</code>, iterated over with <code>foreach</code>, etc.)
Another implementation that's slightly more terse:
<
while { $data != [set data [join $data]] } { }
return $data
}
puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
# ===> 1 2 3 4 5 6 7 8</
=={{header|Trith}}==
<
{{omit from|UNIX Shell}}
=={{header|TXR}}==
An important builtin.
<
@(bind bar foo)
@(flatten bar)</
Run:
Line 3,898 ⟶ 4,125:
=====Implementation=====
<syntaxhighlight lang="vb">
class flattener
dim separator
Line 3,931 ⟶ 4,158:
end property
end class
</syntaxhighlight>
=====Invocation=====
<syntaxhighlight lang="vb">
dim flat
set flat = new flattener
flat.itemSeparator = "~"
wscript.echo join( flat.flatten( array( array( 1 ),2,array(array(3,4),5),array(array(array())),array(array(array(6))),7,8,array())), "!")
</syntaxhighlight>
{{out}}
Line 3,948 ⟶ 4,175:
=====Alternative (classless) Version=====
{{works with|Windows Script Host|*}}
<syntaxhighlight lang="vbscript">
' Flatten the example array...
a = FlattenArray(Array(Array(1), 2, Array(Array(3,4), 5), Array(Array(Array())), Array(Array(Array(6))), 7, 8, Array()))
Line 3,964 ⟶ 4,191:
Next
End Sub
</syntaxhighlight>
=={{header|V (Vlang)}}==
{{trans|PL/I}}
<syntaxhighlight lang="Zig">
fn main() {
arr := "[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]"
println(convert(arr))
}
fn convert(arr string) []int {
mut new_arr := []int{}
for value in arr.replace_each(["[","","]",""]).split_any(", ") {if value !="" {new_arr << value.int()}}
return new_arr
}
</syntaxhighlight>
{{out}}
<pre>
[1, 2, 3, 4, 5, 6, 7, 8]
</pre>
=={{header|Wart}}==
Here's how Wart implements <code>flatten</code>:
<
if no.seq
acc
Line 3,974 ⟶ 4,221:
(cons seq acc)
:else
(flatten car.seq (flatten cdr.seq acc))</
{{out}}
Line 3,981 ⟶ 4,228:
=={{header|WDTE}}==
<
let s => import 'stream';
Line 3,990 ⟶ 4,237:
})
-> s.collect
;</
'''Usage:'''
<
{{out}}
Line 4,001 ⟶ 4,248:
{{libheader|Wren-seq}}
A method already exists for this operation in the above module.
<
var a = [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
System.print(Lst.flatten(a))</
{{out}}
Line 4,010 ⟶ 4,257:
[1, 2, 3, 4, 5, 6, 7, 8]
</pre>
=={{header|zkl}}==
<
fcn(i){ if(List.isType(i)) return(Void.Recurse,i,self.fcn); i}) }
flatten(L(L(1), L(2), L(L(3,4), 5), L(L(L())), L(L(L(6))), 7, 8, L()))
//-->L(1,2,3,4,5,6,7,8)</
This works by recursively writing the contents of lists to a new list. If a list is recursive or cyclic, it will blow the stack and throw an exception.
|