zero323 commented on a change in pull request #27406: 
[SPARK-30681][PYSPARK][SQL] Add higher order functions API to PySpark
URL: https://github.com/apache/spark/pull/27406#discussion_r373485315
 
 

 ##########
 File path: python/pyspark/sql/functions.py
 ##########
 @@ -2840,6 +2840,367 @@ def from_csv(col, schema, options={}):
     return Column(jc)
 
 
+def _invoke_higher_order_function(name, cols, funs):
+    """
+    Invokes expression identified by name,
+    (relative to ```org.apache.spark.sql.catalyst.expressions``)
+    and wraps the result with Column (first Scala one, then Python).
+
+    :param name: Name of the expression
+    :param cols: a list of columns
+    :param funs: a list of tuples ((*Column) -> Column, Iterable[int])
+                 where the second element represent allowed arities
+
+    :return: a Column
+    """
+    sc = SparkContext._active_spark_context
+    expressions = sc._jvm.org.apache.spark.sql.catalyst.expressions
+    expr = getattr(expressions, name)
+
+    jcols = [_to_java_column(col).expr() for col in cols]
+    jfuns = [_create_lambda(f, a) for f, a in funs]
+
+    return Column(sc._jvm.Column(expr(*jcols + jfuns)))
+
+
+@since(3.0)
+def transform(col, f):
+    """
+    Returns an array of elements after applying a transformation to each 
element in the input array.
+
+    :param col: name of column or expression
+    :param f: a function that is applied to each element of the input array.
+        Can take one of the following forms:
+
+        - Unary ``(x: Column) -> Column: ...``
+        - Binary ``(x: Column, i: Column) -> Column...``, where the second 
argument is
+            a 0-based index of the element.
+
+        and can use methods of :class:`pyspark.sql.Column`, functions defined 
in
+        :py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``.
+        Python ``UserDefinedFunctions`` are not supported
+        (`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__).
+
+    :return: a :class:`pyspark.sql.Column`
+
+    >>> df = spark.createDataFrame([(1, [1, 2, 3, 4])], ("key", "values"))
+    >>> df.select(transform("values", lambda x: x * 2).alias("doubled")).show()
+    +------------+
+    |     doubled|
+    +------------+
+    |[2, 4, 6, 8]|
+    +------------+
+
+    >>> def alternate(x, i):
+    ...     return when(i % 2 == 0, x).otherwise(-x)
+    >>> df.select(transform("values", alternate).alias("alternated")).show()
+    +--------------+
+    |    alternated|
+    +--------------+
+    |[1, -2, 3, -4]|
+    +--------------+
+    """
+    return _invoke_higher_order_function("ArrayTransform", [col], [(f, {1, 
2})])
+
+
+@since(3.0)
+def exists(col, f):
+    """
+    Returns whether a predicate holds for one or more elements in the array.
+
+    :param col: name of column or expression
+    :param f: an function ``(x: Column) -> Column: ...``  returning the 
Boolean expression.
+        Can use methods of :class:`pyspark.sql.Column`, functions defined in
+        :py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``.
+        Python ``UserDefinedFunctions`` are not supported
+        (`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__).
+    :return: a :class:`pyspark.sql.Column`
+
+    >>> df = spark.createDataFrame([(1, [1, 2, 3, 4]), (2, [3, -1, 
0])],("key", "values"))
+    >>> df.select(exists("values", lambda x: x < 
0).alias("any_negative")).show()
+    +------------+
+    |any_negative|
+    +------------+
+    |       false|
+    |        true|
+    +------------+
+    """
+    return _invoke_higher_order_function("ArrayExists", [col], [(f, {1})])
 
 Review comment:
   That would work, but
   
   - we have `aggregate` case which takes two functions, and I wanted to avoid 
unnecessary type checks or proliferation of utility functions (and we don't 
seem to use dispatching). It means we need at least 
`_invoke_higher_order_function("ArrayExists", [col], [f])`
   - Checking arguments requires some fun with `inspect`, which is version 
specific (2.7 sigh...), and it would have to be repeated in both.
   - DRY ‒ that's the same line for each variant.
   
   I guess we could build lambdas before invoking, roughly like this
   
   ```python
   jf = _create_lambda(func=f, expected_nargs={1})
   return _invoke_higher_order_function("ArrayExists", [col], [jf])
   ```
   
   but I am still not fond of repeating this all over the place.
   
   > looks potentially somewhat confusing
   
   If intention is not clear I'd prefer
   
   ```python
   from collections import namedtuple 
   
   _LambdaSpec = namedtuple("_LambdaSpec", ["func", "expected_nargs"])
   ```
   
   and then
   
   ```python
   return _invoke_higher_order_function(
       "ArrayExists",
       [col],
       [_LambdaSpec(func=f, expected_nargs={1})])
   ```

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to