Recursively unzip a list into items

I have a list and would like to return each item from it individually. Basically, how to pop out of the stack. For instance:

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 repeating, I would really like to return each integer one by one until the list becomes empty. So basically something like:

 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 to use something bend or scan were unsuccessful. For example, this simply returns a list (same as a map).

 let pop3 (rnds:int list) = let rec pop3' rnds acc = match rnds with | head :: tail -> List.tail(tail) | [] -> acc pop3' [] rnds 
+5
source share
2 answers

This seems like 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" 
+2
source

Will uncons do what you need?

 let uncons = function h::t -> Some (h, t) | [] -> None 

You can use it to “pop” the head of the list:

 > rnds |> uncons;; val it : (int * int list) option = Some (66, [17; 93; 33; 17; 21; 1; 49; 5; 96]) 

You can repeat this:

 > rnds |> uncons |> Option.bind (snd >> uncons);; val it : (int * int list) option = Some (17, [93; 33; 17; 21; 1; 49; 5; 96]) > rnds |> uncons |> Option.bind (snd >> uncons) |> Option.bind (snd >> uncons);; val it : (int * int list) option = Some (93, [33; 17; 21; 1; 49; 5; 96]) 
+5
source

Source: https://habr.com/ru/post/1243640/


All Articles