Use of functional Haskell-like Accumulator in javascript functions -
i'm looking haskell , i'm fascinated of features, example end-recursive functions using accumulator.
questions:
- is there construct in javascript similar that? or make sense regarding efficiency since javascript not functional haskell?
- is there library ramda, lodash, ... supports way of programming
and if so, how write example in javascript:
power_acc :: double -> int -> double power_acc x y = power_acc_h x y 1 power_acc_h :: double -> int -> double -> double power_acc_h x 0 acc = acc power_acc_h x y acc = power_acc_h x (y-1) (acc*x)
is there construct in javascript similar that?
yes, can literally translate js:
function power_acc(x, y) { // double -> int -> double y = y>>>0; // cast positive int (avoiding nontermination) return power_acc_h(x, y, 1); } function power_acc_h(x, y, acc) { // double -> int -> double -> double return y == 0 ? acc : power_acc_h(x, y-1, acc*x); }
or make sense regarding efficiency since javascript not functional haskell?
with es6, tail recursion supported in js, , you'll same efficiency loop (and possibly better haskell, don't create lazy multiplications).
is there library ramda, lodash, ... supports way of programming
no library required. although i'm sure there libs simplify type checking or offer nicer notation pattern matching.
how write example in javascript?
you'd use while
loop. accumulation functions in haskell written way because can directly optimised loop, , that's notation should use construct in js (as programmers familiar it):
function power_acc(x, y) { // double -> int -> double y = y>>>0; // cast positive int (avoiding nontermination) var acc = 1; while (y != 0) { acc *= x; y -= 1; } return acc; }
mutating local variables no harm, function still pure. if you're looking shorter notation, use for
loop.
Comments
Post a Comment