Skip to content

Ninety-Nine Haskell Problems, but in Javascript (1-10)

In an effort to work on my functional JS chops I’ve been solving the 99 Haskell problems (or Scala, Prolog, etc.) in Javascript. Here’s problems 1-10 using Immutable.JS

Problem 1: Find the last element of a list

const last = (n) => {
  return (n.size == 1) ? n : last(n.rest());
}

Problem 2: Find the last but one element of a list

const lastButOne = (n) => {
  return (n.size == 2) ? n.first() : last(n.rest());
}

Problem 3: Find the kth element of a list

const kth = (l, i) => {
  return (i > 1) ?
    kth(l.rest(), i-1) : l.first()
}

Problem 4: Find the number of elements in a list

const len = (n) => {

  const aux = (n, i) => {
    return (n.size > 0) ?
      aux(n.rest(), i+1) : i;
  }
  return aux(n, 0);

}

Problem 5: Reverse a list

const rev = (n) => {

  return (n.size == 1) ?
    n.first() : List(n.last())
            .concat(rev(n.slice(0, n.size-1)))

}

Problem 6: Find out whether a list is a palindrome

const palindrome = (l1) => {

  const compare = (a1, a2) => {

    return !a1.map((el, idx) => {
      return (el == a2.get(idx))
    }).includes(false)

  }

  return compare(l1, rev(l1))
}

Problem 7: Flatten a nested list structure

const flatten = (l1) => {

  return l1.reduce((acc, el) => {
    return acc.concat((el.constructor === List) ? flatten(el) : el)
  }, List([]));

}

Problem 8: Eliminate consecutive duplicates of list elements

const elim = (l1) => {

    return l1.filter((el, i) => {

      if ((el == l1.get(i+1)) == false) {
        return el;
      }

    });

}

Problem 9: Pack consecutive duplicates of list elements into sublists.

const pack = (l1) => {

  const aux = (acc, cur, l2) => {

    if (l2.size == 0) {
      return acc.concat(List([cur]));
    }

    if (l2.get(0) == cur.get(0)) {
      return aux(acc, cur.concat(l2.get(0)), l2.rest());
    } else {
      return aux(acc.concat(List([cur])), List([l2.get(0)]), l2.rest());
    }

  }

  return aux(List([]), List([]), l1).rest()

}

Problem 10: Run-length encoding of a list.

const rle = (l1) => {
  return pack(l1).map((el) => {
    return List([el.size, el.get(0)])
  })
}
Published injavascript

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *