Flatten a list: Difference between revisions

Icon example
No edit summary
(Icon example)
Line 324:
 
-- output [1,2,3,4,5,6,7,8]</lang>
 
=={{header|Icon}}==
The following procedure solves the task using a string representation of nested lists. It's uses several library routines and cares not if the list is well formed or not.
<lang Icon>link strings # for compress,deletec,pretrim
 
procedure sflatten(s) # uninteresting string solution
return pretrim(trim(compress(deletec(s,'[ ]'),',') ,','),',')
end</lang>
This procedure is more in the spirit of the task handling actual lists rather than representations. It uses a recursive approach and some of the built-in list manipulation functions and operators.
<lang Icon>procedure flatten(L) # in the spirt of the problem a structure
local l,x
 
l := []
every x := !L do
if type(x) == "list" then l |||:= flatten(x)
else put(l,x)
return l
end</lang>
 
Finally a demo routine to drive these and a helper to show how it works.
<lang Icon>procedure main()
write(sflatten(" [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]"))
writelist(flatten( [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]))
end
 
procedure writelist(L)
writes("[")
every writes(" ",image(!L))
write(" ]")
return
end</lang>
 
=={{header|Ioke}}==
Anonymous user