Loop over multiple arrays simultaneously: Difference between revisions
Logo |
added haskell |
||
Line 15:
'(a b c)
'(1 2 3))</lang>
If lists are different lengths, it stops after the shortest one.
=={{header|Haskell}}==
<lang haskell>main = mapM_ putStrLn $ zipWith3 (\a b c -> [a,b,c]) "abc" "ABC" "123"</lang>
<tt>zipWith</tt> (2 lists) and <tt>zipWith3</tt> are exported by Prelude. <tt>zipWith4</tt> through <tt>zipWith7</tt> are available in the <tt>Data.List</tt> module.
If lists are different lengths, it stops after the shortest one.
|
Revision as of 18:53, 6 August 2009
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
Loop over multiple arrays (or lists or tuples ...) and print the ith element of each. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Example, loop over the arrays (a,b,c)
, (A,B,C)
and (1,2,3)
to produce the output
aA1 bB2 cC3
If possible, also describe what happens when the arrays are of different lengths.
Common Lisp
<lang lisp>(mapc (lambda (&rest args)
(format t "~{~A~}~%" args)) '(|a| |b| |c|) '(a b c) '(1 2 3))</lang>
If lists are different lengths, it stops after the shortest one.
Haskell
<lang haskell>main = mapM_ putStrLn $ zipWith3 (\a b c -> [a,b,c]) "abc" "ABC" "123"</lang> zipWith (2 lists) and zipWith3 are exported by Prelude. zipWith4 through zipWith7 are available in the Data.List module.
If lists are different lengths, it stops after the shortest one.
J
(,.":"0)&:>/ 'abc' ; 'ABC' ; 1 2 3
Logo
<lang logo> show (map [(word ?1 ?2 ?3)] [a b c] [A B C] [1 2 3]) ; [aA1 bB2 cC3]
(foreach [a b c] [A B C] [1 2 3] [print (word ?1 ?2 ?3)]) ; as above, one per line </lang>
Python
Using zip(): <lang python>>>> print ( '\n'.join(.join(x) for x in zip('abc', 'ABC', '123')) ) aA1 bB2 cC3 >>> </lang> If lists are different lengths, zip() stops after the shortest one.
Using map(): <lang python>>>> print ( '\n'.join(map(lambda *x: .join(x), 'abc', 'ABC', '123')) ) aA1 bB2 cC3 >>> </lang> If lists are different lengths, map() pretends that the shorter lists were extended with None items.
Ruby
<lang ruby>['a','b','c'].zip(['A','B','C'], [1,2,3]).each {|i,j,k| puts "#{i}#{j}#{k}"}</lang> or <lang ruby>['a','b','c'].zip(['A','B','C'], [1,2,3]).each {|a| puts a.join()}</lang> If lists are different lengths, .zip() stops at the end of the object it is called on (the first list). If any other list is shorter, it pretends that they were extended with nil items.
Tcl
<lang tcl>foreach i {a b c} j {A B C} k {1 2 3} {
puts "$i$j$k"
}</lang>