[Swift-devel] Problem with iterate
Mihael Hategan
hategan at mcs.anl.gov
Sun Feb 21 13:28:59 CST 2010
On Sun, 2010-02-21 at 08:37 +0000, Ben Clifford wrote:
> > And then ML would just have full static scoping, so whatever is visible
> > in the scope of foo's definition is visible in its invocation.
>
> But that only works if your variables are visible. For static parameters,
> sure. But:
>
> foreach p1 in [1,2,3] { foreach p2 in [10,20,30] { o[p1][p2] = p1 + p2 }}
>
> o = map outerbody [1,2,3]
>
> outerbody p = map innerbody [10,20,30]
You're not using p there
>
> innerbody q = q + ?
outerbody p = map innerbody zip [10, 20, 30] replicate 3 p
innerbody p q = p + q
Or you could deal with nested foreaches by merging the values into
tuples:
body p q = p + q
p = map body cross [1, 2, 3] [10, 20, 30]
where we'd define:
cross a b = map (\c -> zip b replicate length b c) a
Either way it kinda looks like gibberish if you're not used to it.
>
> So you end up wanting to define innerbody inside the scope of outerbody,
Right, so we'd need proper closures.
>
> outputbody p = let
> innerbody q = q + p
> in map innerbody [10,20,30]
>
> which looks pretty un-c-like indeed.
> But I guess something like that is
> necessary if you want to access loop variables from nested loops (which I
> think is desirable).
There's also the list comprehension way with C-like syntax, which
involves no array indices:
o = list(
foreach p in [1, 2, 3] {
list(
foreach q in [10, 20, 30] {
p + q;
}
)
}
)
More information about the Swift-devel
mailing list