1 / 5
Settings
<<<>>>
Both keepPositive and keepEven use very similar patterns of computation. Given a list ns, they return a new list by applying a boolean-valued "filtering" function (i.e., isPos for keepPositive and isEven for keepEven) to every element of the given list. This is done by applying the filtering function to the head of the list and, if that value passes the filter test, then consing it onto what recursion returns from the tail of the list. This pattern is highlighted in red below.
- -1
- -8
- 4
- 3
ns
- var isPos = function (n) {
- return fp.isGT(n, 0);
- };
- var keepPositive = function (ns) {
- if (fp.isNull(ns))
- return [ ];
- else if (isPos(fp.hd(ns)))
- return fp.cons(fp.hd(ns),
- keepPositive(fp.tl(ns)));
- else
- return keepPositive(fp.tl(ns));
- };
- keepPositive( [-1, -8, 4, 3] );
- var isEven = function (n) {
- return fp.isZero(n % 2);
- };
- var keepEven = function (ns) {
- if (fp.isNull(ns))
- return [ ];
- else if (isEven(fp.hd(ns)))
- return fp.cons(fp.hd(ns),
- keepEven(fp.tl(ns)));
- else
- return keepEven(fp.tl(ns));
- };
- keepEven( [-1, -8, 4, 3] );