I have implemented a lazy infinite sequence function along with 3 functions called take,reduce,map. the take function is similar to Haskell's implementation where it takes a finite sequence from the infinite sequence given a finite value and the usual reduce and map functions in Javascript that works with the finite sequence type.
Now I'm trying to evaluate values in the sequence with various conditions applied to the sequence values.
I'm stuck at implementing functions that takes in a number term and calculate the sequence total product and sum with every alternating sequence value sign is changed to a negative sign. Here's the function I implemented for that objective:
function alternatingProduct(term) {
return reduce((x, y) => x * y, take(term, map(x => -x, generateSequence((v) => (v + 1))(1))), 1);
}
How the function supposed to work is it takes in the sequence lazily and changes every alternate value sign from positive to negative. So when sequence of 1 to 3 is generated for example, the 2 in the sequence should be negative, giving a total product of the whole finite sequence an answer of -6.
Initially I thought my code is working when I called
alternatingProduct(4)
//where it returns 24.
alternatingProduct(3)
//where it returns -6.
When i tried to implement a similar function to sum instead, that's when I realised my function is wrong.
function alternatingSum(term) {
return reduce((x, y) => x + y, take(term, map(x => -x, generateSequence((v) => (v + 1))(1))), 0);
}
alternatingSum(3)
//should return 2 because of 1+(-2)+3 but it returned 5 instead
alternatingSum(4)
//should return -2 because of 1+(-2)+3+(-4) but it returned -9 instead
Now I realised my function map changes every value in the sequence. I have no ideas how to change my code to only change alternating values of a lazy sequence. I am new to lazy sequence and evaluation and just experimenting with it so any help is appreciated
You can just use
map(x => x%2 ? x : -x, …)
so that odd values are kept and even values are negated.