other-languages 2024-04-29

This is one-level flatten in Python:

def flatten(lst):
    return [e for es in lst for e in es]

For some reason I have a hard time grasping it 😕

First part, e for es in lst is simple - but then it seems the last part for e in es ... hm ... somhow operates on the same es? But that e is a different e?

these are written in a DSL that's like nested loops but without the indentation

return [e for es in lst for e in es] can be read like this:

ret = []
for es in lst:
    for e in es:
      ret.append(e)
return ret

👍 1

that is to say the [e for ...] is like saying append to a new list each of e. and then for es in lst and for e in es are two for loops but flattened into the list comprehension

clojure does it in the reverse: (for [es lst e es] e)

💡 1

for es in lst, for e in es, return a sequence of e

Ah, yes so it's read as

python'ish
for es in lst
   for e in es
      e
so
clojure
(for [es lst
        e es]
   e)

👍 1