lib: introduce foreach = flip map

The main purpose is to bring attention to `flip map`, which improves
code readablity. It is useful when ad-hoc anonymous function
grows two or more lines in `map` application:

```
      map (lcfg:
        let port = lcfg.port;
            portStr = if port != defaultPort then ":${toString port}" else "";
            scheme = if cfg.enableSSL then "https" else "http";
        in "${scheme}://cfg.hostName${portStr}"
      ) (getListen cfg);
```
Compare this to `foreach`-style:
```
      foreach (getListen cfg) (lcfg:
        let port = lcfg.port;
            portStr = if port != defaultPort then ":${toString port}" else "";
            scheme = if cfg.enableSSL then "https" else "http";
        in "${scheme}://cfg.hostName${portStr}"
      );
```
This is similar to Haskell's `for` (http://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Traversable.html#v:for)
This commit is contained in:
danbst 2019-07-14 13:17:49 +03:00
parent 696767a9c9
commit 69920dafbf
2 changed files with 14 additions and 1 deletions

View file

@ -71,7 +71,7 @@ let
zipAttrsWithNames zipAttrsWith zipAttrs recursiveUpdateUntil
recursiveUpdate matchAttrs overrideExisting getOutput getBin
getLib getDev chooseDevOutputs zipWithNames zip;
inherit (lists) singleton foldr fold foldl foldl' imap0 imap1
inherit (lists) singleton foreach foldr fold foldl foldl' imap0 imap1
concatMap flatten remove findSingle findFirst any all count
optional optionals toList range partition zipListsWith zipLists
reverseList listDfs toposort sort naturalSort compareLists take

View file

@ -21,6 +21,19 @@ rec {
*/
singleton = x: [x];
/* Apply the function to each element in the list. Same as `map`, but arguments
flipped.
Type: foreach :: [a] -> (a -> b) -> [b]
Example:
foreach [ 1 2 ] (x:
toString x
)
=> [ "1" "2" ]
*/
foreach = xs: f: map f xs;
/* right fold a binary function `op` between successive elements of
`list` with `nul' as the starting value, i.e.,
`foldr op nul [x_1 x_2 ... x_n] == op x_1 (op x_2 ... (op x_n nul))`.