foreach animal { "dog" "cat" "bird" } color { "brown" "black" "red" } { puts "See the $color $animal?" }
foreach animal { "dog" "cat" "bird" } color { "brown" "black" "red" } { puts "See the $color $animal?" }
(loop :for animal :in '("dog" "cat" "bird")
:for color :in '("brown" "black" "red")
:do (format t "See the ~a ~a?~%" color animal))
See the brown dog?
See the black cat?
See the red bird?
How far can we take the example? (loop :for animal :in '("dog" "cat" "bird")
:for color :in '("brown" "black" "red")
:for count :from 2
:do (format t "See the ~a ~a ~as?~%" count color animal))
See the 2 brown dogs?
See the 3 black cats?
See the 4 red birds?
How about this? (loop :for animal :in '("dog" "cat" "bird")
:for color :in '("brown" "black" "red")
:for count :from 2 :sum count :into total
:do (format t "See the ~a ~a ~as?~%" count color animal)
:finally (format t "See all ~a?~%" total))
See the 2 brown dogs?
See the 3 black cats?
See the 4 red birds?
See all 9?
Anybody?People either love or hate Common Lisp's LOOP. Lispy types who prefer recursion often abhor it. I'm a lover.
for animal, color in zip(['dog', 'cat', 'bird'], ['brown', 'black', 'red']):
print 'See the %s %s?' % (color, animal)Still, I wish more languages directly imitated the TCL foreach loop. I've found that when I code, I wish I could just do some simple task 3-4 times. I am always tempted to create a little function, and to call that function repeatedly. But that seems like overkill. With TCL, I just write a simple loop statement instead of the function. I've found that my code is more compact, and the number of functions that I declare is reduced.
['dog', 'cat', 'bird'].zip(['brown', 'black', 'red']).each {|animal, color| puts "See the #{color} #{animal}?"} a:`dog`cat`bird
c:`brown`black`red
{`0:,//("See the ";$x;" ";$y;"?\n")}'[c;a]
The string formatting is a bit ugly because I'm not using a dedicated format function, but foreach with multiple data structures is just f'[list;of;arguments].In other words, it's one character: ' ("each").
for animal, color in zip(['dog', 'cat', 'bird'], ['brown', 'black', 'red']): print 'See the %s %s?' % (color, animal)
edit: eurleif beat me too it.
(doseq [[a c] (zip ["dog" "cat" "bird"] ["brown" "black" "red"])] (print "See the " c a "?"))
Haskell:
mapM_ (\(a, c) -> putStrLn $ "See the " ++ c ++ " " ++ a ++ "?") (zip ["dog", "cat", "bird"] ["brown", "black", "red"])
edit: one can do way more complicated stuff with the list monad in Haskell and the very comprehensive core lib in Clojure; I'm sure even these examples can still be made a little bit shorter and more readable.
for <dog cat bird> Z <brown black red> -> $animal, $color {
say "See the $color $animal?"
} (doseq [animal ["dog" "cat" "bird"
color ["brown" "black" "red"]]
(printf "see the %s %s?\n" color animal))