0

After studying most of The Little Schemer, I've been trying my hand at some recursive solutions to Coderbyte challenges.

After some fiddling I threw in cons and thought my upperConsIt would work to look through an array, find all of the instances of a particular letter and capitalize each. Ultimately, I'll have an array that I can convert into a string with that one letter now capitalized.

Thee ERROR pops up when I try to use shift() like cdr. Why is this? What would I have to do to work with JavaScript recursively in this case?

'use strict';
var newArray = [];
var originalText = 'i will eat my sausage if i can';
var arrayToProcess = textIntoArray(originalText);

function cons(a, d) {
  return [a, d];
}

function textIntoArray(string) {
  return string.split('');
}

function upperConsIt(array, letter) {
  return array[0] === null ? null :
    array[0] === letter ? cons(array[0].toUpperCase(), upperConsIt(array.shift(), letter)) :
    cons(array[0], upperConsIt(array.shift(), letter));
}


upperConsIt(arrayToProcess, 'i');

console.log(arrayToProcess);

phantom.exit();

Here is the error output:

TypeError: undefined is not a constructor (evaluating 'array.shift()')

I just don't see how this is a type error. The array should be an array, right?

4

1 回答 1

0

列表是 2 个元素的嵌套数组['t',['e',['s',['t',null]]]]

拆分使['t', 'e', 's', 't'].

array.shift()变异。你真的应该使用这样的东西:

function car(cons) {
  return cons[0];
}

function cdr(cons) {
  return cons[1];
}
于 2015-05-19T23:25:18.573 回答