prql icon indicating copy to clipboard operation
prql copied to clipboard

Functions - syntax, scope and limitations

Open snth opened this issue 4 years ago • 29 comments

In issue #437 we ended up with quite a lot of discussion around the syntax for functions. For anyone browsing the issue log that might be quite difficult to find so I'm opening a separate issue for it here. The syntax also gets updated in PR #442 .

The current syntax is described in: https://github.com/prql/prql/blob/main/reference/src/functions.md

@aljazerzen also gave some descriptions on Discord which I've reproduced below:

Currently they are limited to "any expression", but there are plans for them to allow:

  • "late binding variables"
func net gross = gross * (1 - tax)

from finances
select [net gross_salaries, net gross_materials, net gross_something]

where tax is column from the finances, but is not resolved until after the function is materialised

  • currying
func add a b = a + b
func add_one = add 1

from employees
select [ age_next_year: add_one age ]
  • transform functions
func take_first col = (sort col | take 1)

from employees
take_first age

snth avatar May 03 '22 10:05 snth

The function syntax seems like the least polished aspect of PRQL to me so far. While it has a lot of really elegant ideas from functional languages, my worry is that it's a bit too esoteric for beginners and might confuse them. In my experience, SQL is often something non-programmers pick up coming from Excel and it would be great if we could appeal to those people as well. So while we want to enable concise and logical expression of data pipelines for experienced users, we should also aim to make PRQL easy to pickup for beginners.

I have a number of ideas/comments which are likely to be controversial so I'll break them up into separate comments in oder to make it easier to indicate what you disagree or agree with.

snth avatar May 03 '22 10:05 snth

I like the maxim from the Zen of Python that "There should be one– and preferably only one –obvious way to do it.".

With currying and pipelining I fear that there may be multiple ways of expressing the same thing which may be confusing to beginners. I think the currying in particular is not very beginner friendly.

Also since we're going with the whole pipeline approach, shouldn't we see if we can double down on that and force that for all function applications?

So instead of

group [title, country_code] (
  aggregate [
    average salary,
  ]
)

have

group [title, country_code] (
  aggregate [
    salary | average,
  ]
)

?

snth avatar May 03 '22 10:05 snth

I'm not a big fan of the | symbol for pipelines. While I know it's standard in the unix shell and Jinja templates for example, it's also often used for logical OR and unions in type definitions. Also in regexes | is a separator between alternatives so that's what my mind often jumps to.

Moreover there is no intrinsic indicator to a newcomer in which direction the flow of data is. I think something like >> would make that more obvious, e.g.

group [title, country_code] (
  aggregate [
    salary >> average,
  ]
)

snth avatar May 03 '22 10:05 snth

  • transform functions
func take_first col = (sort col | take 1)

from employees
take_first age

I think this is a bad idea. What happens when I put this in a derive block?

func take_first col = (sort col | take 1)

from employees
derive [
  min_age = take_first age,
  seniority = age - min_age,
]

Will that work? I guess maybe it unrolls it into CTE or a subquery? At this stage I don't understand enough about the compiler and how it works. However I see PRQL mostly as a more convenient way to write SQL so I would prefer to keep it at the level where I can predict the SQL that will come out of it.

I would also prefer it if the top level commands in the left column of data pipelines remain keywords so that one can quickly scan a pipeline to see what transformations take place. take_first in this example breaks that.

Therefore I propose that functions remain expressions that can be used anywhere within an expression.

If there really is a need for naming common pipeline steps then maybe introduce another language construct for that such as macros or subpipelines or something like that.

snth avatar May 03 '22 10:05 snth

Coming to the function syntax and examples from #437

func add x::number to::number:1 ::number = x + to

or

func (add x::number to::number=1)::number = x + to

I propose the following:

func add = (x:number, to:number=1) : number => x + to

or

func add = (x:number, to:number=1) => x + to : number 

basically using the JS, Typescript () => ... syntax for functions. I think that very clearly and visually demonstrates that some values are used to produce a new value which should be understandable for newcomers.

snth avatar May 03 '22 11:05 snth

Let me lay a mental framework of how I think about the functions.

Functions are actually the core of the language, but remain hidden because of subtle syntax of the function call. Pipeline in PRQL means a series of functions and relational means that they operate on tabular data/tables/dataframes.

So when working on compiler I realized that pipeline transforms actually are normal functions, one could define as (using pseudo-Rust):

type Frame = HashMap<String, Vec<T>>

fn from(name: Ident) -> Frame {
	Frame { }
}

fn derive((alias, expr), frame: Frame) -> Frame {

	frame.alias = match expr {
		Ident(i) => frame[i],
		ScalarFunction(f(column)) => {
			frame.column.map(f)
		}
		VectorFunction(f(column)) => {
			f(frame.column)
		}
	}

	frame
}
	
fn aggregate((alias, expr), frame: Frame) -> Frame {
	new_frame = {}
	new_frame.alias = match expr {
		AggregationFunction(f(column)) => {
			[ f(frame.column) ]
		}
	}

	new_frame
}

fn multiply(factor: float, value: float) -> float {
	factor * value
}

fn sum(column: Vec<float>) -> float {
	column.iter().sum()
}

fn lag(column: Vec<float>) -> Vec<float> {
	column.insert_front(null)
	column.remove_back()
}

Now, pipeline is just a different notation of turning foo(bar(x)) into x | bar | foo.

from employess
derive [
	net_salary: multiply 0.8 gross_salary
]
aggregate [
	total: sum net_salary
]

is equivalent to:

frame = from(employess)
frame = derive((net_salary, multiply(0.8)), frame)
frame = aggregate((total, sum()), frame)

Here derive x is a function call of function derive with one argument. Because derive expects two parameters, this call evaluates to a curry: a function that still expects one argument. This makes it possible to use this expression in a pipeline.

aljazerzen avatar May 03 '22 11:05 aljazerzen

I very strongly agree with "There should be one– and preferably only one –obvious way to do it."

I see how it goes against currying and I do actually think that inline pipeline, currying and transform functions are all advanced features that should remain hidden for average user. To go even further I think that a linter should discourage use of single-function pipelines. This way, simple queries will almost never contain | symbol.

But for power-users, functional programming offers a well-defined and concise language. Such users are likely to be familiar with notion that | represents a pipe.

aljazerzen avatar May 03 '22 11:05 aljazerzen

So applying the previous suggestion to the examples from PR #442 in https://github.com/prql/prql/blob/99898cac610eff157dd65bc43e283f331703e729/reference/src/functions.md:

func (celsius_of_fahrenheit temp) = (temp - 32) * 3

from cities
derive temp_c = (celsius_of_fahrenheit temp_f)

becomes

func celsius_from_fahrenheit = (temp) => (temp - 32) * 3

from cities
derive [
  temp_c1 = temp_f >> celsius_from_fahrenheit,
  temp_c2 = celsius_from_fahrenheit(temp_f),

For functions with multiple parameters, I don't think it's always practical to have the main argument as the last parameter so I propose to use _ as a placeholder to indicate which parameter should be substituted with the previous pipeline step when using the pipeline syntax.

So

func (interp lower=0 higher x) = (x - lower) / (higher - lower)

from students
derive [
  sat_proportion_1 = (interp 1600 sat_score),
  sat_proportion_2 = (interp lower=0 1600 sat_score),
]

becomes

func interp = (x, lower=0, higher) => (x - lower) / (higher - lower)

from students
derive [
  sat_proportion_1 = interp(sat_score, 0, 1600),
  sat_proportion_2 = sat_score >> interp(_, lower=0, 1600),
]

snth avatar May 03 '22 11:05 snth

Regarding function transforms: actually my function definition example was not entirely correct:

- func take_first col = (sort col | take 1)
+ func take_first col frame:Frame = (frame | sort col | take 1)

Your example would now produce a type error, because a call of take_first would be missing the frame argument.

Note that this is not meant for average user. It's the hidden tool that advanced used can leverage. It is also very logical production of how PRQL works.

It may seem that this makes PRQL unpredictable in its SQL output, but in essence, our functions are just macros - substitution of ident with an expression. It's just that in this case, use have a macro that substitutes frame transforms.

aljazerzen avatar May 03 '22 11:05 aljazerzen

I propose the following:

func add = (x:number, to:number=1) : number => x + to

Of course! => is very obvious. I'm quite surprised we did not think of it before :D

What do you think about ->? It's used in Java & Rust.

Is there a reason for = after function name? I would prefer for function definition to be as close to function call, because that gives feeling of language consistency.

func add x:number to:number=1 => x + to

aljazerzen avatar May 03 '22 11:05 aljazerzen

https://github.com/prql/prql/issues/444#issuecomment-1115992366

Ok, having the frame parameter does make it clearer and alleviates my concern around that I think.

snth avatar May 03 '22 11:05 snth

https://github.com/prql/prql/issues/444#issuecomment-1116002602

No particularly strong feelings on => vs ->. I don't know Rust and JS has => so that's what I went with. Happy with either.

func add x:number to:number=1 => x + to

I find the lack of parentheses and commas confusing to be honest. Like why are there no commas separating parameters because we have those everywhere else like in [ , ] expressions etc...?

To me having the = makes sense because if you think of functions as first-class objects then it's just another assignment to a name which just happens to have a function on the right hand side. I was initially going to propose doing away with the func and just have something like

add = (x:number, to:number=1) => x + to

but I saw a comment from you somewhere that it's nice to have the func in the left column so one can just use that to scan for function definitions quickly so I kept it.

So I find the = makes sense because add and (x:number, to:number=1) => x + to are equal in that you should be able to use each interchangeably, so in my syntax the following should give the same results:

func add = (x, to=1) => x + to

from transactions
derive [
  total_1 = add(cost, markup),
  total_2 = ((x, to=1) => x + to)(cost, markup),
]

snth avatar May 03 '22 11:05 snth

Then let's rather use ->, because ⇒ means implication in math.


Oh, that does make sense: everything has the syntax of lambda function.

@max-sixty wanted to have a language accessible to non-programmers, so he made function calls not use any punctuation. And that decision goes well with functional programming aspect of PRQL, because pipeline transforms have the same syntax.

With that in mind, what about:

func add = x to=1 -> x + to

from transactions
derive [
  total_1 = add cost markup,
  total_2 = cost markup | x to=1 -> x + to,
]

I've changed total_2 to inline pipeline, because function calls can only be parsed if they have ident as first term, preventing having a lambda function instead of function name.

But now, cost markup would be parsed as a function call... Ah. This no-punctuation rule is hard to keep consistent.

aljazerzen avatar May 03 '22 12:05 aljazerzen

I sign off for a few hours and the PRQL has completely changed! Jokes aside, this is a good discussion, thank you.


func add = x to=1 -> x + to
  • This is interesting

  • The punctuation between add and the arguments is reasonable and consistent with the rest of the language, even if it's not consistent with Ocaml, the original inspiration.

  • We do end up quite close to just doing a lambda:

    derive add = ([x, to=1] -> x + to)
    

    ...i.e. transform a list of args to an expression, and there's no need for func.

    I think there are reasons to not pursue this — lambda functions are much less helpful in PRQL than most languages, because all operations happen on arrays / columns already. We don't need to map (x, y) => (x + 2y) over a list, because PRQL & SQL already just accept time + 2*overtime, where time and overtime are arrays. So I think it's quite unlikely people will be using lambda functions inline.

  • I'm not a great fan of using the = for both the add = and the to= — it's difficult to visualize where the break is. I think we should use it once there. And maybe use : for the other, like:

    func add = x to:1 -> x + to
    

    This would be consistent with having aliases & assigns use different punctuation from named args

  • Maaaybe we need parentheses around x to=1 -> x + to to ensure the -> binds tighter than the = in func add =?


cost markup | x to=1 -> x + to,

Pipelines can never pass more than value (at least how I'm thinking about them). They can pass tuples, but I don't think we need that language feature.


Re => vs ->: no strong view — IIRC JS does => and Java does ->. Rust only uses -> in the type definition.


While roundly condemned last time I brought it up, indentation would work!

func add x y
  x + y
func lag_day x
  group sec_id
    sort date
    window
      lag 1 x

(ok ok, I'll try not to bring it up again)


I very strongly agree with "There should be one– and preferably only one –obvious way to do it."

I see how it goes against currying and I do actually think that inline pipeline, currying and transform functions are all advanced features that should remain hidden for average user. To go even further I think that a linter should discourage use of single-function pipelines. This way, simple queries will almost never contain | symbol.

But for power-users, functional programming offers a well-defined and concise language. Such users are likely to be familiar with notion that | represents a pipe.

100% agree with @aljazerzen here + his previous comment

max-sixty avatar May 04 '22 01:05 max-sixty

Trying to add things up into some options across this & https://github.com/prql/prql/issues/444 (though good idea to keep them as separate issues originally), some broad clusters of options:

  1. Status quo — don't change anything, use :: for annotations
    func::number interp lower:0 higher x::number = (x - lower) / (higher - lower)
    
    from s:students
    derive [
      sat_proportion_1: (interp 1600 sat_score),
      sat_proportion_2: (interp lower:0 1600 sat_score),
    ]
    
  2. Use : for Named args, = for Aliases & Assigns, :: for annotations: Note that we can dispense with the parentheses in the derive for this & the next couple.
    func::number interp = lower:0 higher x::number -> (x - lower) / (higher - lower) 
    
    from s=students
    derive [
      sat_proportion_1 = interp 1600 sat_score,
      sat_proportion_2 = interp lower:0 1600 sat_score,
    ]
    
  3. Use = for Named args, = for Aliases & Assigns, :: for annotations:
    func::number interp = lower:0 higher x::number -> (x - lower) / (higher - lower)
    
    from s=students
    derive [
      sat_proportion_1 = interp 1600 sat_score,
      sat_proportion_2 = interp lower:0 1600 sat_score,
    ]
    
  4. I'm going to put one more out there — use <> for types. They are used for generic in Rust, but impl Point<i32> is correct and similar to what we're doing, and lets us use : more clearly for other things. Use : for Named args, = for Aliases & Assigns, <> for annotations:
    func<number> interp = lower:0 higher x<number> -> (x - lower) / (higher - lower)
    
    from s=students
    derive [
      sat_proportion_1 = interp 1600 sat_score,
      sat_proportion_2 = interp lower:0 1600 sat_score,
    ]
    

(We don't need to define => vs -> / parentheses around funcs / = after func name / arguments-as-lists, etc here — this is for the issues where we face tradeoffs between different threads)

As you look through, weigh the main query 5x higher than the func, and the func 5x higher than the type annotations!

max-sixty avatar May 04 '22 02:05 max-sixty

Just to follow-up on this:

@max-sixty wanted to have a language accessible to non-programmers, so he made function calls not use any punctuation. And that decision goes well with functional programming aspect of PRQL, because pipeline transforms have the same syntax.

Right — general purpose languages have lots of punctuation, because they need lots of widgets — lists & tuples & sets & dicts. The two types of languages without lots of punctuation:

  • Functional languages like Ocaml, where the language is very small and most things are implementations
  • DSLs like SQL, which have limited semantics

So I envisage PRQL as a DSL for analytical queries — centering around the notion of a pipeline, removing SQL's warts, adding functions & variables, and keeping features like bare words (select foo rather than select "foo"). And so appealing both to 1) advanced users who miss basic features, tire of the warts, and have seen languages which don't need to be complicated, and 2) beginners who don't want to learn lots of punctuation[^1].

One piece of feedback I'm open to is: not having as much punctuation makes it more complicated to read or learn. But it's important not to have that as a first reaction only because it's different from Python & Java. So I would want to hear what people like @aljazerzen think, who has spent a lot of time writing the lang.

[^1]: e.g. for a toy example: why do python functions need colons at the end?

Check out Ocaml functions for more (and labeled arguments too!)

max-sixty avatar May 04 '22 04:05 max-sixty

Function calls and pipeline

After some thinking, I concluded that we must keep pipeline transforms' syntax the same as normal function calls for consistency, much simpler compiler. This limits us with syntax on lambda functions, but as @max-sixty pointed out, they are not really needed in this language, because expressions of select and derive are already treated as functions applied to the whole column.

Equals

I've persuaded that conceptually, named args, assigns and equality comparisons are different things and should hence have different syntax. Python confuses this a bit with their named args. So this crosses out options 1. and 3.

I would also avoid 4., because <> may be needed for generic types: func sum col::column<number> -> ...

This leaves option 2. The most important part here - the query - indeed looks the most readable of all options to me to me:

derive [
  sat_proportion_1 = interp 1600 sat_score,
  sat_proportion_2 = interp lower:0 1600 sat_score,
]

(about scoping with indentation: I would still avoid it)

aljazerzen avatar May 04 '22 12:05 aljazerzen

2 gets my vote!

qorrect avatar May 04 '22 13:05 qorrect

I agree that the most readable option is

  1. Use : for Named args, = for Aliases & Assigns, :: for annotation

so Named Args get a different symbol from Aliases and Assigns.

Just one idea (since I'm not shy about throwing wacky ones out there), what about ~ for Named Args, that way we could still keep : for annotations?

So instead of

func::number interp = lower:0 higher x::number -> (x - lower) / (higher - lower) 

have

func:number interp = lower~0 higher x:number -> (x - lower) / (higher - lower) 

I'm not aware of : being used for named args in (m)any languages so we wouldn't be going against an established convention and this would allow us to keep with the convention of having : for type annotations.

One use of ~ is for "distributed as" in statistics (e.g. X~N(0,1)) so here we would just have the parameter distributed according to a singleton distribution of the default value. Anyway, it's a bit of a stretch I know but it would be nice to keep the : annotations as I find the :: introduces a bit of line noise.

snth avatar May 04 '22 13:05 snth

https://github.com/prql/prql/issues/444#issuecomment-1116910865

Thanks. I had a look at OCaml functions because I don't know OCaml at all.

In 2.4.2 he writes

We now have two ways we could write an increment function:

let inc x = x + 1
let inc = fun x -> x + 1

It seems that the function syntax we have arrived at is very close to the second form (apart from moving the fun(c) token to the front and not requiring this be in a let/derive block).

I feel quite strongly that the first form is not very intuitive to beginners and should not be supported in PRQL. There is nothing inherent in the notation to suggest that the first name is the name of the function and the remaining names are the names of parameters.

I agree that lambdas/anonymous functions are probably not going to play a big role in PRQL but I think the syntax quite intuitively communicates that you are dealing with a mapping.

One case where I think lambdas could come up is when trying to apply transformations, so if we have a rule that function transformation always apply to the last or first parameter then you might want to define a lambda just ahead of that to move the parameter you are interested in, into the required position (if you can't specify it otherwise). Not sure if that scenario would really ever come up but it's the main case I could think of.

While on the OCaml syntax, in section 2.4.6 of that link, he says

Here are two equivalent ways of squaring 6:

square (inc 5);;
5 |> inc |> square;;

So OCaml uses |> for the pipeline operator. As mentioned elsewhere, I'm not a fan of the | for the pipeline operator and would prefer something like |> or >> which gives a visual indication of the data flow similar to the %>% in dplyr and R.

snth avatar May 04 '22 13:05 snth