Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Function composition in JS

Name: Anonymous 2012-09-27 1:26

Is there a smarter/better way to write this?


function c() {
    var fs = arguments;
    return function(x) {
        return Array.prototype.reduceRight.call(fs, function(x, f) {
            return f(x);
        }, x);
    }
}

Name: Anonymous 2012-09-27 1:29

>>1
that's pretty much what you want.

Name: Anonymous 2012-09-27 2:15

>>2
I was kind of annoyed that all that line noise was necessary just to use reduceRight. One consequence of OOP is that functions are imprisoned inside classes but at least javascript provides .call to let you freely pass in "this" of your choice.

Name: Anonymous 2012-09-27 2:21

the power of javascript :D

Name: Anonymous 2012-09-27 2:22

ihbt

Name: Anonymous 2012-09-27 2:40

Fucking disgustingly ugly.

Name: Anonymous 2012-09-27 2:50

>>6

I know right.

Name: Anonymous 2012-09-27 2:53

>>6,7
you two say this as though your toy languages are capable of doing this

Name: Anonymous 2012-09-27 3:02

>>8

I was agreeing with 7 that JS is ugly. Even Java will soon have better lambda syntax.

Name: Anonymous 2012-09-27 4:17

>>8
You're right, my toy languages are incapable of looking like such pigshit.

Name: Anonymous 2012-09-27 4:45

>>3
One consequence of OOP is that functions are imprisoned inside classes
Wrong.
(defgeneric reduce-right (f xs x))
(defmethod reduce-right (f (xs sequence) x)
  (reduce f xs :from-end t :initial-value x))
  (reduce f xs :from-end t))

(defun compose (&rest fs)
  (lambda (x)
    (reduce-right #'funcall fs x)))

Actually, Common Lisp doesn't even requires you to use CLOS here since reduce is already parametrised for sequences. Please also note that if this were production code, a compiler macro would optimise away as much funcall calls as possible. Enjoy your toy language.

Name: 11 2012-09-27 4:46

Copypaste mistake, delete the fourth line.

Name: Anonymous 2012-09-27 5:58

Just use compose from underscore.js

Name: Anonymous 2012-09-27 6:17

>>3
You mean bad OOP

Name: Anonymous 2012-09-27 15:52

bump

Don't change these.
Name: Email:
Entire Thread Thread List