Search code examples
recursionf#mutable

Recursively unpack list into elements


I have a list and would like to return each element from it individually. Basically like popping from a stack. For example:

let rnd = new System.Random()
let rnds = List.init 10 (fun _ -> rnd.Next(100))
List.iter (fun x -> printfn "%A"x ) rnds

However instead of iterating, I would actually like to return each integer one after the other until the list is empty. So basically something along the lines of:

List.head(rnds)
List.head(List.tail(rnds))
List.head(List.tail(List.tail(rnds)))
List.head(List.tail(List.tail(List.tail(List.tail(rnds)))))

Unfortunately my attempts at a recursive solution or even better something using fold or scan were unsuccessful. For example this just returns the list (same as map).

let pop3 (rnds:int list) =
    let rec pop3' rnds acc =
        match rnds with
        | head :: tail -> List.tail(tail)
        | [] -> acc
    pop3' [] rnds

Solution

  • This seems like a good oppurtunity for a class

    type unpacker(l) = 
        let mutable li = l
        member x.get() = 
            match li with
            |h::t -> li<-t;h
            |_ -> failwith "nothing left to return"