Flatten a list: Difference between revisions

m (→‎Recursive: finish revert.)
Line 1,036:
{ 1 2 3 4 5 6 7 8 }
 
=={{header|FantomForth}}==
{{works with|Forth}}
Works with any ANS Forth.
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
<lang forth>include FMS-SI.f
include FMS-SILib.f
include FMS-SILib-extras.f
 
: flatten \ { list1 list2 -- }
<lang fantom>
locals| list2 list1 |
class Main
list1 size: 0 ?do i list1 at:
{
dup [is-a] object-list2 0=
// uses recursion to flatten a list
if list2 addobj: else list2 recurse then loop ;
static List myflatten (List items)
{
object-list2 list
List result := [,]
o{ o{ 1 } 2 o{ o{ 3 4 } 5 } o{ o{ o{ } } } o{ o{ o{ 6 } } } 7 8 o{ } }
items.each |item|
list flatten
{
list p: \ o{ 1 2 3 4 5 6 7 8 } ok</lang>
if (item is List)
result.addAll (myflatten(item))
else
result.add (item)
}
return result
}
public static Void main ()
{
List sample := [[1], 2, [[3,4], 5], [[[,]]], [[[6]]], 7, 8, [,]]
// there is a built-in flatten method for lists
echo ("Flattened list 1: " + sample.flatten)
// or use the function 'myflatten'
echo ("Flattened list 2: " + myflatten (sample))
}
}
</lang>
 
=={{header|Fortran}}==