简体   繁体   English

如何通过模式匹配实现地图

[英]How to implement map with pattern matching

I wanted to write a pattern matching implementation of map , so I wrote this: 我想编写一个map的模式匹配实现,所以我这样写:

const map = (f, [x, ...xs]) => {
  return (!x && !xs) ? [] : [f(x), ...map(f, xs)];
}

However, the compiler complains about the xs parameter in the recursive call: 但是,编译器在递归调用中抱怨xs参数:

Argument of type 'any[]' is not assignable to parameter of type '[any, ...any[]]'. 类型“ any []”的参数不能分配给类型“ [any,... any []]”的参数。 Property '0' is missing in type 'any[]' 类型“ any []”中缺少属性“ 0”

I also tried [f(x), ...map(f, [xs])] , but this produces a stack overflow error. 我也尝试过[f(x), ...map(f, [xs])] ,但这会产生堆栈溢出错误。

What am I doing wrong? 我究竟做错了什么?

If I understand correctly, I think the issue was the comparison of the ...xs argument via &&, that caused the recursion to never end. 如果我理解正确,我认为问题是通过&&对... xs参数的比较,这导致递归永远不会结束。 You only really care about if the next array prop to handle is there, the rest will be caught by the next recursion. 您只真正在乎下一个要处理的数组prop是否存在,其余的将被下一个递归捕获。

The compiler error comes from there being no type definition for the argument array, and tsc deduces one from the source: but the type [any, ...any[]] is too narrow. 编译器错误是由于参数数组没有类型定义而引起的,而tsc从源代码中推论出一种:但是类型[any,... any []]太窄。 Typing the array with :any[] clears the issue. 用:any []键入数组可以解决问题。

I hope this helps. 我希望这有帮助。

const map = (f, [x, ...rest]:any[]) => {
  return (!x) ? [] : [f(x), ...map(f, rest)];
}

console.log(map(x=>x+10, [1,2,3]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM