1
\$\begingroup\$

Solution to 99 lisp problems: P08, with functional javascript

If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed.

* (compress '(a a a a b c c a a d e e e e))
 (A B C A D E)


Anyone want to review?

function cond( check, _then, _continuation ) {
 if(check) return _then( _continuation )
 else return _continuation()
}
function compress( list ) {
 return (function check( index, item, nextItem, compressed ) {
 return cond( item !== nextItem, function _then( continuation ) {
 compressed = compressed.concat([ item ])
 return continuation()
 },
 function _continueation() {
 return cond(!nextItem, function _then() {
 return compressed
 }, 
 function _continuation() {
 return check( index + 1, list[index + 1], list[index + 2], compressed ) 
 })
 })
 })( 0, list[0], list[1], [] )
}

ref:
http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html

asked Jul 23, 2012 at 1:51
\$\endgroup\$
2
  • \$\begingroup\$ Wouldn't a loop or recursive calling be a better idea? \$\endgroup\$ Commented Jul 23, 2012 at 5:19
  • \$\begingroup\$ The cond function can probably be replaced with a ternary operator and switching the order a little. \$\endgroup\$ Commented Jul 23, 2012 at 5:20

1 Answer 1

1
\$\begingroup\$

I don't think you need so much complexity in javascript. It's not a fully functional language, don't try to make it so.

var arr = [
 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'd', 'a', 'e', 'e', 'e'
];
arr = arr.filter( function( el, i ) {
 // return if the current isn't the same as the next
 return el !== arr[ i + 1 ];
});
console.log( arr ); // ["a", "b", "c", "d", "a", "e"]

This is 2 lines.

answered Jul 23, 2012 at 8:01
\$\endgroup\$
1
  • \$\begingroup\$ The function passed to filter can be generalized by adding a third parameter arr. \$\endgroup\$ Commented Jul 26, 2012 at 1:10

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.