j3-fortran / fortran_proposals

Proposals for the Fortran Standard Committee
175 stars 14 forks source link

Allow array comprehension syntax in implied do loop #244

Open omaclaren opened 2 years ago

omaclaren commented 2 years ago

I would love the ability to do array comprehensions (a la Julia), i.e. the analogue of list comprehensions (Python, Haskell etc) in modern Fortran. This would be a syntactic extension to implied do loops as discussed here:

https://fortran-lang.discourse.group/t/array-comprehensions-in-fortran/2517

A suggested syntax (with example implementation) is given in this thread:

https://fortran-lang.discourse.group/t/array-comprehensions-in-fortran/2517/10

which is:

lhs = [(some_expression(i), i = initial, final, step where condition(i))]

The thread also discusses why do concurrent doesn't quite work for this, even though it supports a condition (in short, the size and indexing of the array satisfying the condition are not known in advance).

This is also essentially a shorthand for (the more functional programming version):

a = [(i = initial, final, step)]
b = pack(some_expression(a), condition(a))

but avoids having to explicitly construct a and then filter (pack) it. Array/list comprehensions are widely used for array construction as well as data analysis in e.g. Python.

Finally, this relates somewhat to issues https://github.com/j3-fortran/fortran_proposals/issues/116 and https://github.com/j3-fortran/fortran_proposals/issues/241, in that these + the current syntax might allow expressions like

[(some_expression(ai), for ai in array where condition(ai))]

which would allow for even more simple, flexible array construction/filtering in the style of list comprehensions.

I believe these extensions are very much in the 'spirit' of expressing mathematical concepts in modern Fortran, being based directly on the mathematical concept of set comprehensions, e.g. (https://en.wikipedia.org/wiki/List_comprehension)

It follows the form of the mathematical set-builder notation (set comprehension) as distinct from the use of map and filter functions

while also being close to an existing construct (implied do loops).

Thanks!

(edit: fixed some typos)

certik commented 2 years ago

Thanks for proposing this! I've been missing exactly this feature from Fortran also.

jvdp1 commented 2 years ago

Similarly to this idea, there is also trueloc and falseloc recently introduced in stdlib