zed icon indicating copy to clipboard operation
zed copied to clipboard

user-defined functions (UDF)

Open mccanne opened this issue 3 years ago • 1 comments

The time has come to implement a simple form of user-defined function.

We can debate the syntax but I propose this pythonic form:

def f(x,y,...): ( <any expression>)

We need parens to define the scope of the expression (since we don't use whitespace scoping like python)

In the initial implementation no recursion or control structures will be allowed. This can come later. For now, we will support just the existing expression syntax.

mccanne avatar Jul 22 '22 02:07 mccanne

A community zync user recently expressed a need for this functionality.

philrz avatar Sep 29 '22 16:09 philrz

Verified in Zed commit 5f4c4e8.

Here's an example that uses two UDF functions. One uses a regular expression to extract the area code from a phone number string and the other computes a factorial recursively.

$ cat functions.zed 
func factorial(n): (
  n == 1 ? 1 : n*factorial(n-1)
 )

func area_code(str): (
  regexp(/^\((\d{3})\) *(\d{3}\-\d{4})$/, str)[1]
)

$ zq -version
Version: v1.3.0-31-g5f4c4e81

$ echo '{"num": 5, "phone": "(415) 555-1212"}' | zq -Z -I functions.zed 'yield {num, fac:factorial(num), phone, area_code:area_code(phone)}' -
{
    num: 5,
    fac: 120,
    phone: "(415) 555-1212",
    area_code: "415"
}

Documentation is at https://zed.brimdata.io/docs/next/language/overview#4-func-statements.

Thanks @mattnibs!

philrz avatar Dec 16 '22 17:12 philrz