是否可以从数字类型T
中获得具有T + 1值的数字类型Y
。
type one = 1
type Increment<T extends number> = ???
type two = Increment<one> // 2
P.S。目前,我已经对增量值进行了硬编码,但是问题是硬编码的,因此受到限制:
export type IncrementMap = {
0: 1,
1: 2,
2: 3,
答案 0 :(得分:2)
我只是这样硬编码:
import java.io.PrintStream;
import java.util.*;
public class CombinationCalc<T> {
private void getSubsets(List<T> input, int length, int index, Set<T> currentSet, List<Set<T>> solution) {
if (currentSet.size() == length) {
solution.add(new HashSet<>(currentSet));
return;
}
if (index == input.size()) {
return;
}
T x = input.get(index);
currentSet.add(x);
getSubsets(input, length, index + 1, currentSet, solution);
currentSet.remove(x);
getSubsets(input, length, index + 1, currentSet, solution);
}
public List<Set<T>> getSubsets(List<T> input, int length) {
List<Set<T>> solution = new ArrayList<>();
getSubsets(input, length, 0, new HashSet<>(), solution);
return solution;
}
public void printSolution(List<Set<T>> solution, PrintStream ps) {
Iterator<Set<T>> solutionIterator = solution.iterator();
ps.print("[");
if (!solutionIterator.hasNext()) {
ps.print("]");
}
while (solutionIterator.hasNext()) {
Set<T> solutionEntry = solutionIterator.next();
Iterator<T> setEntry = solutionEntry.iterator();
ps.print("[");
if (!setEntry.hasNext()) {
ps.print("]");
}
while (setEntry.hasNext()) {
T entry = setEntry.next();
ps.print(entry);
if (setEntry.hasNext()) {
ps.print(", ");
} else {
ps.print("]");
}
}
if (solutionIterator.hasNext()) {
ps.print(", ");
} else {
ps.print("]");
}
}
ps.println();
}
public static void main(String[] args) {
CombinationCalc<Integer> calc = new CombinationCalc<>();
List<Integer> input = Arrays.asList(1, 2, 3, 4, 5);
List<Set<Integer>> solution = calc.getSubsets(input, 3);
calc.printSolution(solution, System.out);
}
}
正如我在其他评论中所说的那样,目前没有对这种自然递归类型的大力支持。我would love it是否受支持,但不存在。在实践中,我发现如果某个东西可以处理长达20个左右的元组就足够了,但是您的经验可能会有所不同。
无论如何,如果有人在这里提出了一个不是经过硬编码但也可以对任意数字进行处理并表现良好的解决方案(其中type Increment<N extends number> = [
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,
38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54, // as far as you need
...number[] // bail out with number
][N]
type Zero = 0
type One = Increment<Zero> // 1
type Two = Increment<One> // 2
type WhoKnows = Increment<12345>; // number
的评估结果为Increment<123456789>
),我很想看见。也许将来有一天它将成为语言的一部分。
希望有所帮助;祝你好运!
答案 1 :(得分:0)
此解决方案不是硬编码的,但由于 TypeScript 的递归限制而没有用。当我测试它时,它不能处理大于 45 的 Number2Nat
。
type SomeNat = [...unknown[]];
type Zero = [];
type Succ<N extends SomeNat> = [...N, unknown];
type Nat2Number<N extends SomeNat> = N["length"];
type Dec<N extends SomeNat> = N extends [unknown, ...infer T] ? T : never;
type Add<N extends SomeNat, M extends SomeNat> = [...N, ...M];
type Sub<N extends SomeNat, M extends SomeNat> = M extends Zero ? N : Sub<Dec<N>, Dec<M>>;
type Number2Nat<I extends number, N extends SomeNat = Zero> = I extends Nat2Number<N> ? N : Number2Nat<I, Succ<N>>;