From 95fef311a3d652bd17e20ce2e211cdad86d60b50 Mon Sep 17 00:00:00 2001 From: Henry Zhu Date: Sat, 23 Dec 2023 11:39:00 +0800 Subject: [PATCH] Add a challenge for variadic generics (#76) --- .../advanced-variadic-generics/question.py | 21 +++++++++++++++ .../advanced-variadic-generics/solution.py | 26 +++++++++++++++++++ .../advanced-variadic-generics/solution2.py | 23 ++++++++++++++++ 3 files changed, 70 insertions(+) create mode 100644 challenges/advanced-variadic-generics/question.py create mode 100644 challenges/advanced-variadic-generics/solution.py create mode 100644 challenges/advanced-variadic-generics/solution2.py diff --git a/challenges/advanced-variadic-generics/question.py b/challenges/advanced-variadic-generics/question.py new file mode 100644 index 0000000..4d60921 --- /dev/null +++ b/challenges/advanced-variadic-generics/question.py @@ -0,0 +1,21 @@ +""" +TODO: + +Define an `Array` type that supports element-wise addition of arrays with identical dimensions and types. +""" + + +class Array: + def __add__(self, other): + ... + + +## End of your code ## +from typing import assert_type + +a: Array[float, int] = Array() +b: Array[float, int] = Array() +assert_type(a + b, Array[float, int]) + +c: Array[float, int, str] = Array() +assert_type(a + c, Array[float, int, str]) # expect-type-error diff --git a/challenges/advanced-variadic-generics/solution.py b/challenges/advanced-variadic-generics/solution.py new file mode 100644 index 0000000..b2fbca5 --- /dev/null +++ b/challenges/advanced-variadic-generics/solution.py @@ -0,0 +1,26 @@ +""" +TODO: + +Define an `Array` type that supports element-wise addition of arrays with identical dimensions and types. +""" + +from typing import Generic, TypeVar, TypeVarTuple, assert_type + +T = TypeVar("T") +Ts = TypeVarTuple("Ts") + + +class Array(Generic[*Ts]): + def __add__(self, other: "Array[*Ts]") -> "Array[*Ts]": + ... + + +## End of your code ## +from typing import assert_type + +a: Array[float, int] = Array() +b: Array[float, int] = Array() +assert_type(a + b, Array[float, int]) + +c: Array[float, int, str] = Array() +assert_type(a + c, Array[float, int, str]) # expect-type-error diff --git a/challenges/advanced-variadic-generics/solution2.py b/challenges/advanced-variadic-generics/solution2.py new file mode 100644 index 0000000..2d08ea4 --- /dev/null +++ b/challenges/advanced-variadic-generics/solution2.py @@ -0,0 +1,23 @@ +""" +TODO: + +Define an `Array` type that supports element-wise addition of arrays with identical dimensions and types. +""" + +from typing import assert_type + + +class Array[*Ts]: + def __add__(self, other: "Array[*Ts]") -> "Array[*Ts]": + ... + + +## End of your code ## +from typing import assert_type + +a: Array[float, int] = Array() +b: Array[float, int] = Array() +assert_type(a + b, Array[float, int]) + +c: Array[float, int, str] = Array() +assert_type(a + c, Array[float, int, str]) # expect-type-error