如何使用模式匹配实现地图
How to implement map with pattern matching
想写一个map
的模式匹配实现,所以写了这个:
const map = (f, [x, ...xs]) => {
return (!x && !xs) ? [] : [f(x), ...map(f, xs)];
}
但是,编译器在递归调用中抱怨 xs
参数:
Argument of type 'any[]' is not assignable to parameter of type '[any,
...any[]]'. Property '0' is missing in type 'any[]'
我也试过[f(x), ...map(f, [xs])]
,但这会产生堆栈溢出错误。
我做错了什么?
如果我没理解错的话,我认为问题出在通过 && 比较 ...xs 参数,导致递归永远不会结束。您只真正关心下一个要处理的数组属性是否存在,其余的将被下一个递归捕获。
编译器错误是因为参数数组没有类型定义,而 tsc 从源代码中推导出一个:但是类型 [any, ...any[]] 太窄了。使用 :any[] 键入数组可以解决问题。
希望对您有所帮助。
const map = (f, [x, ...rest]:any[]) => {
return (!x) ? [] : [f(x), ...map(f, rest)];
}
console.log(map(x=>x+10, [1,2,3]))
想写一个map
的模式匹配实现,所以写了这个:
const map = (f, [x, ...xs]) => {
return (!x && !xs) ? [] : [f(x), ...map(f, xs)];
}
但是,编译器在递归调用中抱怨 xs
参数:
Argument of type 'any[]' is not assignable to parameter of type '[any, ...any[]]'. Property '0' is missing in type 'any[]'
我也试过[f(x), ...map(f, [xs])]
,但这会产生堆栈溢出错误。
我做错了什么?
如果我没理解错的话,我认为问题出在通过 && 比较 ...xs 参数,导致递归永远不会结束。您只真正关心下一个要处理的数组属性是否存在,其余的将被下一个递归捕获。
编译器错误是因为参数数组没有类型定义,而 tsc 从源代码中推导出一个:但是类型 [any, ...any[]] 太窄了。使用 :any[] 键入数组可以解决问题。
希望对您有所帮助。
const map = (f, [x, ...rest]:any[]) => {
return (!x) ? [] : [f(x), ...map(f, rest)];
}
console.log(map(x=>x+10, [1,2,3]))