disco icon indicating copy to clipboard operation
disco copied to clipboard

`2f(n)` parses as `2 * f * n`

Open byorgey opened this issue 2 years ago • 3 comments

This definition yields a type error:

f : N -> N
f(0)
f(n+1) = 2f(n) + 3

It is accepted if we add a * sign in between the 2 and the f. Here's the problem:

Disco> :pretty 2f(n)
2 * f * n 

byorgey avatar Apr 08 '22 17:04 byorgey

So 2f(n) needs to parse as 2 * (f(n)) because function application has higher precedence than multiplication; however, the problem is that since function application and multiplication are both left-associative, this first parses as (2 f) n; then 2 f is resolved to 2 * f and then in turn (2 * f) n is resolved to (2 * f) * n. Indeed, if we had something like 2 x y that would be the correct thing to do. But in this case we need to take advantage of the fact that we still know there are parentheses around n to decide that f(n) is function application.

Off the top of my head I'm not sure of the best way to do this in general. Perhaps we should first turn any sequence of chained juxtapositions into a list, then go from there. Anything that looks like ident ( expr ) should be treated as a function call regardless of what comes to the left of the identifier?

byorgey avatar Apr 11 '22 18:04 byorgey

#71 is related. In fact it seems like this might have worked correctly before https://github.com/disco-lang/disco/commit/5c4cdf15262a0765d4ae87ecfc813246ba6b2fc1 . We need both 2 f(n) to parse as 2 * (f @ n) and also (x+1)(x+2)(x+3) to parse as ((x+1) * (x+2)) * (x+3).

Might be simpler to change fixJuxtMul to work differently: first parse chained juxtapositions as a list. Then go through the list and turn anything that looks like <var> (<exp>) into function application; next find things that look syntactically like multiplication; then everything left is function application.

Hmm, could I just come up with an actual grammar for this? i.e. can I do it in a less ad-hoc way?

M = n | T op | T op T | '(' M ')' | M T
T = x '(' T ')' | M | T T

byorgey avatar Mar 22 '23 15:03 byorgey