Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions manual/src/reference/types/tuple.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,15 @@ print((1,).len()); // 1

## Operators

Like lists, tuples support `in`, `not in`, `==`, `!=`, `<>` and the comparisons `<`, `<=`, `>` and `>=`. Other
operators work on each element, as described below.
Like lists, tuples support `++`, `in`, `not in`, `==`, `!=`, `<>` and the comparisons `<`, `<=`, `>` and `>=`.
`++` puts two tuples together into a new one:

```ndc
let point = (1, "a");
print(point ++ (true,)); // (1,"a",true)
```

Other operators work on each element, as described below.

## Vectorization

Expand All @@ -50,7 +57,6 @@ of the same length, or one side may be a scalar that broadcasts:
print((1, 2) + (3, 4)); // (4,6)
print(-(1, 2, 3)); // (-1,-2,-3)
print((1, 2) + 5); // (6,7)
print(("a", "b") ++ ("c", "d")); // ("ac","bd")
```

This only works for operators, not for function calls: `f((1, 2, 3))` passes
Expand Down
2 changes: 1 addition & 1 deletion ndc_analyser/src/analyser/assignments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl Analyser {
self.vars.resolve(&stored_type),
self.vars.resolve(&right_type),
],
CallKind::Operator,
CallKind::of_operator(operation),
operation,
span,
);
Expand Down
2 changes: 1 addition & 1 deletion ndc_analyser/src/analyser/solver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1761,7 +1761,7 @@ impl Analyser {
/// Whether `call` is an arithmetic operator or a comparison, whose
/// operands are numbers of one type.
fn is_number_operator(call: &CallConstraint) -> bool {
matches!(call.kind, CallKind::Operator | CallKind::Comparison)
matches!(call.kind, CallKind::Operator | CallKind::Whole)
&& match call.arguments.len() {
1 => call.name == "-",
2 => matches!(
Expand Down
12 changes: 6 additions & 6 deletions ndc_analyser/src/analyser/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1055,13 +1055,13 @@ fn a_waiting_call_does_not_commit_to_a_narrower_overload_too_early() {
#[test]
fn a_failed_op_assignment_is_reported_once() {
let globals = [
natives(&[("++", "(String, String) -> String")]),
natives(&[("+", "(String, String) -> String")]),
index_natives(),
]
.concat();
assert_eq!(
errors("let g = fn(xs) { xs[0] ++= \"a\"; }; g([1]);", globals),
vec!["No function called '++' found that matches the arguments 'Int, String'"]
errors("let g = fn(xs) { xs[0] += \"a\"; }; g([1]);", globals),
vec!["No function called '+' found that matches the arguments 'Int, String'"]
);
}

Expand Down Expand Up @@ -1124,11 +1124,11 @@ fn a_waiting_call_does_not_commit_to_an_overload_taking_any_instead() {

#[test]
fn an_operator_waits_while_an_operand_could_still_be_a_tuple() {
// `x ++ "!"` could also apply to each string of a tuple.
let globals = natives(&[("++", "(String, String) -> String")]);
// `x + "!"` could also apply to each string of a tuple.
let globals = natives(&[("+", "(String, String) -> String")]);
assert_eq!(
analyse_last_type_with_globals(
"let suffix = fn(x) => x ++ \"!\"; suffix((\"a\", \"b\"))",
"let suffix = fn(x) => x + \"!\"; suffix((\"a\", \"b\"))",
globals
),
StaticType::Tuple(vec![StaticType::String, StaticType::String])
Expand Down
19 changes: 10 additions & 9 deletions ndc_analyser/src/overloads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,26 @@ use std::borrow::Cow;

/// Whether a call site can fall back to element-wise tuple broadcast when no
/// scalar overload matches the argument types directly. Operator syntax
/// (`a + b`, `-x`, `op=`) is an `Operator`, but for a comparison, and
/// everything else (`f(x)`, dot calls, indexing) is `Regular`.
/// (`a + b`, `-x`, `op=`) is an `Operator`, but for one that takes whole
/// values, and everything else (`f(x)`, dot calls, indexing) is `Regular`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallKind {
Regular,
Operator,
/// A comparison, `<`, `<=`, `>`, `>=`, `<=>` or `>=<`, which compares
/// whole values and never applies to each element of a tuple: two tuples
/// no overload compares, as tuples of two kinds of number, are a type
/// error, not a tuple of what each pair of elements gives.
Comparison,
/// An operator that takes tuples whole and never applies to each of
/// their elements: a comparison, `<`, `<=`, `>`, `>=`, `<=>` or `>=<`,
/// and `++`, which concatenates tuples. Two tuples no overload compares,
/// as tuples of two kinds of number, are a type error, not a tuple of
/// what each pair of elements gives, and so is `("a", "b") ++ "c"`.
Whole,
}

impl CallKind {
/// The kind of a call written with the operator `name`.
#[must_use]
pub fn of_operator(name: &str) -> Self {
if matches!(name, "<" | "<=" | ">" | ">=" | "<=>" | ">=<") {
Self::Comparison
if matches!(name, "<" | "<=" | ">" | ">=" | "<=>" | ">=<" | "++") {
Self::Whole
} else {
Self::Operator
}
Expand Down
17 changes: 17 additions & 0 deletions ndc_stdlib/src/sequence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1249,6 +1249,12 @@ pub mod extra {
move || NativeFunc::Simple(Box::new(move |args| tuple_end(args, name == "first"))),
));
}
env.declare_global_fn(NativeSpec::with_signature(
"++",
"Concatenates two tuples into a new tuple.",
"<..A, ..B>((..A), (..B)) -> (..A, ..B)",
move || NativeFunc::Simple(Box::new(concatenate)),
));
// Each length of the sequences zipped, up to twelve, gets its own
// overload, as Rust's standard library does for tuples.
const LONGEST: usize = 12;
Expand Down Expand Up @@ -1278,6 +1284,17 @@ pub mod extra {

const ZIP_DOCUMENTATION: &str = "Zips two or more sequences together into a list of tuples. The result length is the minimum length of the inputs.";

/// The tuple of the elements of the two tuples in `args`, in order.
fn concatenate(args: &[Value]) -> Result<Value, VmError> {
let [Value::Object(left), Value::Object(right)] = args else {
return Err(VmError::native("expected two tuples".to_string()));
};
let (Object::Tuple(left), Object::Tuple(right)) = (left.as_ref(), right.as_ref()) else {
return Err(VmError::native("expected two tuples".to_string()));
};
Ok(Value::tuple(left.iter().chain(right).cloned().collect()))
}

/// The first or last element of the tuple in `args`.
fn tuple_end(args: &[Value], first: bool) -> Result<Value, VmError> {
let [Value::Object(object)] = args else {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Non-numeric vec: `++` over tuples of strings dispatches per-element.
assert_eq(("a", "b") ++ ("c", "d"), ("ac", "bd"));
assert_eq(("hello", "foo") ++ (" world", "bar"), ("hello world", "foobar"));
// Non-numeric vec: `|` over tuples of sets and booleans dispatches per-element.
assert_eq((%{1}, %{"a"}) | (%{2}, %{"b"}), (%{1, 2}, %{"a", "b"}));
assert_eq((true, false) | (false, false), (true, false));

// Vec over tuples of lists.
assert_eq(([1], [2]) ++ ([3], [4]), ([1, 3], [2, 4]));
assert_eq(([1, 2], []) ++ ([3], [4, 5]), ([1, 2, 3], [4, 5]));
// Vec over tuples of maps.
assert_eq((%{1: "a"}, %{}) | (%{2: "b"}, %{3: "c"}), (%{1: "a", 2: "b"}, %{3: "c"}));
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Each position of a tuple operation takes the overload its elements pick,
// and its result keeps that overload's type: here a list and a string are
// each extended in place.
// expect-output: (4,6.5) [1,2] ab
let t = ([1], "a");
t ++= ([2], "b");
let (xs, s): ([Int], String) = t;
print((1, 2.5) + (3, 4), xs, s);
// and its result keeps that overload's type: here a set is extended in
// place and two Ints are or-ed.
// expect-output: (4,6.5) [1,2] 3
let t = (%{1}, 1);
t |= (%{2}, 2);
let (s, n): (%{Int}, Int) = t;
print((1, 2.5) + (3, 4), s.sorted, n);
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
// scalar op= guarantees: inner Rc mutations stay visible through every
// alias of the originals, and the variable itself still reads as the
// updated value.
let l1 = [1, 2];
let l2 = [3, 4];
let pair = (l1, l2);
let s1 = %{1, 2};
let s2 = %{3, 4};
let pair = (s1, s2);
let outer_alias = pair;
pair ++= ([5], [6]);
// Inner-list mutation visible through the original bindings.
assert_eq(l1, [1, 2, 5]);
assert_eq(l2, [3, 4, 6]);
// Outer alias still sees the same inner lists, now mutated.
assert_eq(outer_alias, ([1, 2, 5], [3, 4, 6]));
pair |= (%{5}, %{6});
// Inner-set mutation visible through the original bindings.
assert_eq(s1, %{1, 2, 5});
assert_eq(s2, %{3, 4, 6});
// Outer alias still sees the same inner sets, now mutated.
assert_eq(outer_alias, (%{1, 2, 5}, %{3, 4, 6}));
// pair itself reads as the updated value.
assert_eq(pair, ([1, 2, 5], [3, 4, 6]));
assert_eq(pair, (%{1, 2, 5}, %{3, 4, 6}));
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
// Per-position vec dispatch: positions can resolve to different scalar
// overloads. Element 0 dispatches `++(List, List)`; element 1 dispatches
// `++(String, String)`. The result tuple has different element types per
// position.
// overloads. Element 0 dispatches `|(%{K: V}, %{K: V})`; element 1
// dispatches `|(Int, Int)`. The result tuple has different element types
// per position.
assert_eq(
([1, 2, 3], "foo") ++ ([4, 5, 6], "bar"),
([1, 2, 3, 4, 5, 6], "foobar")
(%{1, 2}, 4) | (%{3}, 1),
(%{1, 2, 3}, 5)
);

// Same shape, longer axis with three distinct overloads per position.
assert_eq(
([1], "a", [10]) ++ ([2], "b", [20]),
([1, 2], "ab", [10, 20])
(%{1}, 2, false) | (%{2}, 1, true),
(%{1, 2}, 3, true)
);

// Mixed numerics: position 0 stays Int; position 1 needs Number coercion
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// `++` puts two tuples together, each element keeping its type, and
// doesn't apply to each pair of elements as other operators do.
// expect-output: (1,"a",2.5,true) 4 a! ("a","b","c","d") (0,"x",9)
let t = (1, "a") ++ (2.5, true);
let s: String = t[1];
fn wrap(inner) => (0,) ++ inner ++ (9,);
print(t, len(t), s ++ "!", ("a", "b") ++ ("c", "d"), wrap(("x",)));
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// `++=` would give the variable a tuple of another length, which is another type.
// expect-error: found (Int, Int, Int, Int, Int) but expected (Int, Int, Int)
let b = (1, 2, 3);
b ++= (4, 5);
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// `++` takes tuples whole, as the comparisons do: a tuple and a string don't
// concatenate, and `++` doesn't apply to each element instead.
// expect-error: No function called '++' found that matches the arguments '(String, String), String'
print(("a", "b") ++ "c");
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// `++=` takes tuples whole too: it doesn't append to each list in the tuple.
// expect-error: No function called '++' found that matches the arguments '([Int], [Int]), [Int]'
let t = ([1], [2]);
t ++= [3];
Loading