Skip to content

Instantly share code, notes, and snippets.

@skahack
Created September 10, 2011 02:02
Show Gist options
  • Save skahack/1207826 to your computer and use it in GitHub Desktop.
Save skahack/1207826 to your computer and use it in GitHub Desktop.
Haskell like
clone = (n) ->
if Array.isArray(n)
re = [].concat n
else
re = Object.extended({})
for key in n
re[key] = n[key]
re
foldr = (f) -> (x) -> (y) ->
if y.length is 0
x
else
_y = clone(y)
t = _y.shift()
f(t)(foldr(f)(x)(_y))
filter = (f) -> (n) ->
foldr((x) -> (xs) -> if f(x) then [x].concat xs else xs)([])(n)
fst = (n) ->
[].concat n[0]
tail = (n) ->
_n = clone(n)
_n.shift()
_n
lt = (x) -> (y) -> if x < y then true else false
gt = (x) -> (y) -> if x >= y then true else false
qsort = (n) ->
if n.length is 0
[]
else
p = fst n
t = tail n
[].concat(qsort filter(gt p)(t)).concat(p).concat(qsort filter(lt p)(t))
alert qsort([4,7,2,1,6,3,5,8,1,3,5])
@skahack
Copy link
Author

skahack commented Jun 9, 2016

ES6

const clone = n => {
  let re;
  if (Array.isArray(n)) {
    re = [].concat(n);
  } else {
    re = Object.extended({});
    for (key in n) {
      re[key] = n[key];
    }
  }
  return re;
}

const foldr = f => x => y => {
  if (y.length === 0) {
    return x;
  } else {
    const _y = clone(y);
    const t = _y.shift();
    return f(t)(foldr(f)(x)(_y));
  }
}

const filter = f => n =>
  foldr(x => xs => f(x) ? [x].concat(xs) : xs)([])(n)

const fst = n => [].concat(n[0]);

const tail = n => {
  const _n = clone(n);
  _n.shift();
  return _n;
}

const lt = x => y => x < y ? true : false;
const gt = x => y => x >= y ? true : false;

const qsort = n => {
  if (n.length === 0) {
    return [];
  } else {
    const p = fst(n);
    const t = tail(n);
    return []
      .concat(qsort(filter(gt(p))(t)))
      .concat(p)
      .concat(qsort(filter(lt(p))(t)));
  }
}

alert(qsort([4,7,2,1,6,3,5,8,1,3,5]));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment