Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pattern that re-uses a variable rather than creating a new one #184

Open
julianhyde opened this issue Oct 5, 2022 · 1 comment
Open

Comments

@julianhyde
Copy link
Collaborator

It would be useful to add syntactic sugar to re-use a variable in from, constraining the new variable. Consider the following expression to compute all paths of length 2:

(*
   1 -> 2 -> 3
   |    ^    ^
   |    |    |
   +--> 4 ---+
*)
val edges = [(1, 2), (2, 3), (1, 4), (4, 2), (4, 3)];
from (x, y) in edges,
    (y2, z) in edges
  where y = y2
  group x, z;
val it = [{x=4,z=3},{x=1,z=2},{x=1,z=3}] : {x:int, z:int} list

It is inconvenient to have to declare y2 and then immediately constrain it to equal y. With the new same operator, the following would be equivalent:

from (x, y) in edges,
    (same y, z) in edges
  group x, z;
@julianhyde
Copy link
Collaborator Author

same is not just for within from. Here is its use in a function:

fun f (1,  1) = 0
  | f (x, same x) = x
  | f (x,  y) = x + y;
val f = fn : int * int -> int
f (1, 1);
val it = 0: int;
f (2, 2);
val it = 2: int;
fun (2, 3);
val it = 5: int;

In Successor ML, you could achieve a similar effect with a pattern guard (if):

fun f (1, 1) = 0
  | f (x, x2 if x = x2) = x
  | f (x, y) = x + y;

(The effect is not identical: the pattern guard (x, x2 if x = x2) would add x and x2 to scope, whereas (x, same x) would only add x to scope.)

But in Standard ML and current Morel, you would have to expand as follows:

- fun f (1, 1) = 1
=   | f (x, y) = if (x = y) then x else x + y;
val f = fn : int * int -> int
- f (1, 1);
val it = 1 : int
- f (2, 2);
val it = 2 : int
- f (2, 3);
val it = 5 : int

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant