javascript - how to generate lazy iteration thing in typescript -
currently still doing question :
make general purpose infinite sequence initialisation function creates infinite lazy sequences. take parameter function compute next value current value. in other words, should “factory” functions naturalnumbers. thus, if call our function initsequence, initsequence(n=>n+1) return function equivalent naturalnumbers.
this template given
interface lazysequence<t> { value: t; next(): lazysequence<t>; } // implement function: function initsequence<t>(transform: (value: t) => t): (initialvalue: t) => lazysequence<t> { // code here }
so far, code in typescript
interface lazysequence<t> { value: t; next(): lazysequence<t>; } // implement function: function initsequence<t>(transform: (value: t) => t): (initialvalue: t) => lazysequence<t> { // code here ... return () => initsequence(v=>v+1) => lazysequence; }
and seemed code doesn't work accordingly. can help? can make clear explanation regarding lazy evaluation, lazy iteration , lazy things? lot
not sure whether need use given interface or not, seems need generator function. read here.
an example can follows:
// generic infinite sequence generator function. function* infinitesequence<t>(initialvalue: t, transform: (value: t) => t): iterableiterator<t> { while (true) { yield initialvalue; initialvalue = transform(initialvalue); } } // create different sequences using generic sequence generator function. let intsequence = infinitesequence(1, n => n + 1); // sequence of natural numbers console.log(intsequence.next().value); // 1 console.log(intsequence.next().value); // 2 console.log(intsequence.next().value); // 3 let oddsequence = infinitesequence(1, n => n + 2); // sequence of odd numbers console.log(oddsequence.next().value); // 1 console.log(oddsequence.next().value); // 3 console.log(oddsequence.next().value); // 5 let evensequence = infinitesequence(0, n => n + 2); // sequence of numbers console.log(evensequence.next().value); // 0 console.log(evensequence.next().value); // 2 console.log(evensequence.next().value); // 4
update based on op's comment:
as question seems homework, try provide useful hints.
think return type of
initsequence
(initialvalue: t) => lazysequence<t>
, returning() => initsequence(v=>v+1) => lazysequence
, not match required return type. in other words need return function takes value of typet
returns object of typelazysequence<t>
. read arrow functions in here , here.think how can construct object of interface. hint: duck typing. read here.
the last bit of problem construct
next
method ,value
property. notenext
again returns object of typelazysequence<t>
,value
should next value in sequence(this part assuming). noteinitsequence(...)(...)
can return such object.
have fun :)
hope helps.
Comments
Post a Comment