other-languages

grav 2024-04-29T15:29:44.226999Z

This is one-level flatten in Python:

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

grav 2024-04-29T15:29:57.423629Z

For some reason I have a hard time grasping it 😕

grav 2024-04-29T15:30:54.126399Z

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?

2024-04-29T15:35:16.086369Z

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

2024-04-29T15:36:08.594919Z

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
2024-04-29T15:37:10.053309Z

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

2024-04-29T15:38:09.734379Z

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

💡 1
2024-04-29T15:38:24.125639Z

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

grav 2024-04-29T15:38:31.200359Z

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
grav 2024-04-29T15:40:08.304899Z

Thanks @nbtheduke!

2024-04-29T15:40:13.124029Z

glad to help