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?

Gabriel Kunkel
  • 2,643
  • 5
  • 25
  • 47

1 Answers1

0

A list is a nested array of 2 element ['t',['e',['s',['t',null]]]].

Split makes ['t', 'e', 's', 't'].

array.shift() mutates. You really should use something like this this instead:

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

function cdr(cons) {
  return cons[1];
}
Sylwester
  • 47,942
  • 4
  • 47
  • 79
  • I see. So there's really no equivalent to cdr in JavaScript just built in. – Gabriel Kunkel May 20 '15 at 17:41
  • @GabrielKunkel You mean a `cdr` built in that happens to match your chosen `cons` implementation? You could as easily have implemented pairs with objects and `car`, `cdr` as methods. (I would have preferred that) BTW. JavaScript has `map` as a method on arrays, but it doesn't use pairs. – Sylwester May 20 '15 at 22:52
  • I understand. The Little Schemer did help me fully understand recursion, but it doesn't translate to JavaScript without building a library of equivalents first. Basically, you can't really mix The Little Schemer functions and the JavaScript built-in methods. I had thought `map` method was just with underscore.js, but now some of those are part of the ECMA. Thanks. – Gabriel Kunkel May 21 '15 at 18:03