Search code examples
ocamllazy-evaluationlazylist

OcamL lazy list series generating


I've got a problem with this task:

  • Define lazy list lSpec (Ocaml) that contains one 1, two 2, three 3 etc. 1,2,2,3,3,3,4,4,4,4,5,...

As far I have got:

type 'a llist = LNil | LCons of 'a * (unit -> 'a llist);;

let rec lfrom k = LCons (k, function () -> lfrom (k+1));; 

let rec ltake = function  
(0, _) -> []  
| (_, LNil) -> []  
| (n, LCons(x,xf)) -> x::ltake(n-1, xf()) ;;

This function is generating the series of integer based on input numer, eg.

ltake (5,lfrom 30);; 
- : int list = [30; 31; 32; 33; 34] 

The thing that I want to do i to convert function lfrom to create not series of integers, but the series from my task. But I have no idea if there is some pattern to create such series?

Thanks for help in advance.


Solution

  • The code you have now uses just one value k to keep track of where it is in the sequence. Fundamentally this would be enough for the new problem, but using just one number for the state would make things difficult to keep track of.

    You might consider something like:

    let rec lspecfrom (j, k) = . . .
    

    Where j is the number you're working on (1, 2, 3, 4, ...) and k is how many have been generated so far. Then the whole list would be generated by a call lspecfrom (1, 0).