Syntax suggestion for tuples and pattern matching.

Discussion

HI everyone! I recently started thinking about adding tuples and pattern matching in my language. The base syntax is C-like (understand brackets and semicolons). I already have a few special primitives:

  • complex #(xxx) (internally 2 floats on the stack)
  • polar $(xxx) (idem)
  • Vec @(xxx) (internally 3 or 4 floats on the stack)

What would you use for tuples? {{xxx}} @{xxx} or anything else?

The language supports (scopable) switches, but I'd like to turn that into pattern matching, maybe

match (exp, other_exp, ...) {
  case 1, 2 -> some_func();
  default -> other_func();
}

What would you suggest?

Posted Jul 23, 2019, 3:24 PM UTC · edited

925
AthasFuthark•

The overwhelmingly most common notation for tuples is a comma-separated sequence of values enclosed in parentheses: (x, y, z). You need a very good reason to deviate from that, and even in that case, your reason is probably not very good. It's generally worth designing the grammar of a language explicitly so that common notation can be supported, unless the point of a language is specifically to gain an advantage by using specialised or uncommon notation (APL and concatenative languages are good examples of such cases).

In fact, offhand the only language I can think of that has tuples and does not use this notation is Erlang, where tuples are enclosed in curly braces: {x, y, z}. This has the advantage of straightforwardly supporting single-element tuples, but it is much less common than using parentheses.

20
fennecdjayOPGwion Language•

Thanks for your answer. I'd rather avoid parentheses, as it is a (parenthesized) list of expressions in gwion. As for curly braces, they are already used for code blocks. I understand that conforming to standards is good, but I think those would lead to too many conflicts in the grammar.

2
wfdctrl•

Can code blocks appear in the same context as tuples? If not you can easily tell them apart even if you use curlies.

2
fennecdjayOPGwion Language•

Nice catch! Lambdas could appear in the same context, but their syntax is quite different

#! this is valid syntax for lambda expression
\ arg0 arg1 { <<< arg0, arg1 >>>; }
3
[deleted]•

[deleted]

1
Felicia_Svilling•

I'd rather avoid parentheses, as it is a (parenthesized) list of expressions in gwion

Can't you change that?

1
grand_mind1•

TypeScript uses square brackets: [x, y, z]. I'm not familiar with the reasoning behind that choice.

2
PeksyTiger•

I think it's because they're basically arrays is js/ts

6
Uncaffeinated•

TypeScript is designed to be a superset of JS, and in JS you use square brackets.

1
grand_mind1•

Sure, but JavaScript doesn't actually have tuples. You just abuse destructuring to make it look like it does. But I suppose you are still right in that they wanted a syntactically-valid JavaScript program which uses that "feature" to be a tuple in TypeScript.

You definitely have to think a bit differently and make different trade-offs when designing a language intended to have the relationship TS has with JS.

1
Uncaffeinated•

JS uses array literals for the kind of things you would use tuples for in other languages. For example, Map (dict) initialization takes an iteratable of length 2 arrays.

1
Tysonzero•

Personally I prefer that syntax, as tuples are basically just heterogenous arrays, so having them share square bracket syntax and using type inference to choose between them is IMO pretty ideal.

1
grand_mind1•

I think the fact that you can't infer the type on its own is the biggest down side. For example in let x = [y, z], what should be the type of x? Typescript chooses it to be an array which I find inconvenient.

1
Tysonzero•

Haskell takes a much more elegant approach to this problem via typeclasses and bidirectional type inference. You can see it in action with number literals, and with OverloadedLiterals and OverloadedStrings (although they need a bump in power to be able to handle HLists/HArrays).

z = [x, y]

a = List.sort z

b = Set.member w z

If the above is defined z will have a polymorphic type based on the IsList typeclass, and a and b will have type [Foo] and Bool respectively.

Now if you convolute things a bit to something like:

(\z -> (List.sort z, Set.member w z)) [x, y]

Haskell will simply reject it without an explicit higher rank type signature, but the following will work as expected:

(\z -> List.sort z) [x, y]
(\z -> Set.member w z) [x, y]

By bumping the power of the IsList typeclass to something that is parameterized by a list of types rather than a single element type, you can get it to support types like Tuple [Int, Bool] as well.

1
[deleted]•

[deleted]

2
AthasFuthark•

No, not really, unless the cost is very low.

1
Tysonzero•

I would say it depends on how expressive your language is, specifically when it comes to tuples.

If you have a lot of expressivity and tuples are more like heterogenous arrays that support things like mapping a polymorphic function over all elements and concatenating tuples and so on, then I would say you should definitely support single element tuples.

If your language is simple and relatively inexpressive then they are much less needed.

1
skyb0rg•

In Erlang specifically, most functions that have multiple return options return tagged tuples, where the first element is the tag. Because Erlang is not statically typed, you would pattern match on the number of elements in the tuple. So you could distinguish between pattern matching an arbitrary tuple and an arbitrary 1-ary tuple.

ex. example(N) when N < 0 -> { error_neg }; example(0) -> { error_zero }; example(N) -> { ok, N * 2 }.

In a statically typed language it’s not worth it but it can make some code more idiomatic.

1
turdbeat•

The link to your language is broken, you typed `gihub` instead of `github`.

3
fennecdjayOPGwion Language•

Thanks, I did not check it and that is the (obvious) result. Fixing now.

2
mamcx•

Well, what about "tup()"?

2
fennecdjayOPGwion Language•

Kind of an idea. I'm gonna need some function in order to cast objects as tuples. But it'd rather be Object.tup() as I don't encourage/use global functions. The bigger problem with this approach, I think, is that it would not be easy/desirable to have a function call as a type_decl. I need something which can both express a litteral and a type declaration. ... along those line (tuple syntax used here {{ is random)

#! this is a comment

#! a function definition 
fun void test_tuple( {{int, string, float}} x) {
  #! this is the debug print. 
  <<< x[0], x[1], x[2] >>>;
}

#! call that function
{{ 1,"test tuple", 0.1 }} => test_tuple;
1
__fmease__λ•

If you are okay with introducing tup or tuple as a keyword, you can support similar syntax for tuples in both term and type context:

fun void test(tup(int, string, float) x) { … }
tup(1, "test", 0.1) => test;

Personally, I am not a fan of cryptic unrelated symbols like @, $, #, I prefer alphanumeric identifiers which ideally can tell me what they stand for — but I see that most parts of your language are constructed this way. I'd get lost pretty quickly between (), #(), $(), @(), @{}, {{}}, <<<>>>> and so on. My two cents :)

2
fennecdjayOPGwion Language•

I understand the cons of cryptic symbols, but as you said, most of my language is constructed this way, and most of that is inherited from chuck. I don't find it this hard as syntactic coloration (in nano and vim) is of great help in those cases.

So I won't probably go for another keyword. Right now I'm thinking of a Tuple type, inheriting from Object, with variable number of types. Like:

Tuple<~ int, string, float ~> my_tuple;

I'm just taking some time to figure it correctly.

Thanks for your advice.

1
mamcx•

Ok, I forgot to make some context. In my lang I have a single way to express "list" but it cover many backing structs:

array = [1 3 2] // same as [it:Int32; 1 3 2]
typed = [Float; 1 2 3 4]
column = [total:Float; 1 2 3 4]
list = List[1 3 4]
set = Set[Any; 1 "A" true]

The key here is that "List of things" is general (the one you need a syntax) but "array set tables hashsets" etc are concrete.

1
Tysonzero•

Are square brackets used yet? I would say square brackets for list, tuples, sets and arrays (disambiguating via type inference, or if that's not possible then via a prefix).

2
jdh30•

I highly recommend OCaml's tuple syntax:

1, 2, 3

For pattern matching, I am using:

[ patt1 -> expr1
| patt2 -> expr2
| ...
| pattn -> exprn ]

e.g. red-black tree rebalancing:

let rec balance =
    [ B, T(R, T(R, a, x, b), y, c), z, d
    | B, T(R, a, x, T(R, b, y, c)), z, d
    | B, a, x, T(R, T(R, b, y, c), z, d)
    | B, a, x, T(R, b, y, T(R, c, z, d)) -> T(R, T(B, a, x, b), y, T(B, c, z, d))
    | color, a, x, b -> T(color, a, x, b) ]
1