Comprehensions, Where Art Thou?

Claude Pache claude.pache at gmail.com
Mon Aug 11 13:30:51 PDT 2014


Le 11 août 2014 à 21:30, Tab Atkins Jr. <jackalmage at gmail.com> a écrit :

> 
> No, all of Peter's comprehensions are short and easy to comprehend.  Comparing it with Dave's version, I think it's simply a matter of the JS comprehensions requiring more syntax, and crossing the line from "easy to read" to "hard to read".  Here's the one bit in particular that stands out:
> 
> Norvig:
> unitlist = ([cross(rows, c) for c in cols] +
>             [cross(r, cols) for r in rows] +
>             [cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')])
> 
> Herman:
> var unitlist
>   = [for (c of cols)
>        cross(rows, [c])]
>     .concat([for (r of rows)
>                cross([r], cols)])
>     .concat([for (rs of ["ABC","DEF","GHI"])
>                for (cs of ["123","456","789"])
>                  cross(rs.split(""), cs.split(""))]);
> 
> Norvig's is simple and easy to read. Herman's is polluted with additional method calls and more indentation.  If we remove the indentation...
> 
> var unitlist
>   = [for (c of cols) cross(rows, [c])]
>     .concat([for (r of rows) cross([r], cols)])
>     .concat([for (rs of ["ABC","DEF","GHI"]) for (cs of ["123","456","789"]) cross(rs.split(""), cs.split(""))]);
> 
> Now pretend that for-of works on strings... (maybe it already does, for all I know, and Dave was just being paranoid)
> 
> var unitlist
>   = [for (c of cols) cross(rows, c)]
>     .concat([for (r of rows) cross(r, cols)])
>     .concat([for (rs of ["ABC","DEF","GHI"]) for (cs of ["123","456","789"]) cross(rs, cs)]);
> 
> Okay, it's still a little bit harder to read, due to the .concat() calls and their attendant additional parens, and the parens around the for-of bodies, but it's not *terribly* worse.  It's still bad enough that I don't know if I'd write it.

I think I'd have written (without comprehension):

    var unitlist = [...function*() {
        for (let c of cols)
            yield cross(rows, c)
        for (let r of rows)
            yield cross(r, cols)
        for (let rs of ["ABC","DEF","GHI"]) 
            for (let cs of ["123","456","789"]) 
                yield cross(rs, cs)
    }]

although it is somewhat lengthier because of extra `function*`, `let`s and `yield`s.

—Claude


More information about the es-discuss mailing list