简体   繁体   中英

How to implement map with pattern matching

I wanted to write a pattern matching implementation of map , so I wrote this:

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:

Argument of type 'any[]' is not assignable to parameter of type '[any, ...any[]]'. Property '0' is missing in type 'any[]'

I also tried [f(x), ...map(f, [xs])] , but this produces a stack overflow error.

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. You only really care about if the next array prop to handle is there, the rest will be caught by the next recursion.

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. Typing the array with :any[] clears the issue.

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]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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