Sergey Aldoukhov
Sergey Aldoukhov

Reputation: 22744

How to unfold a list into list of lists with yield?

Another impractical exercise... I have a function that unfolds a list into a sequence of lists starting with each list element:

[ 1; 2; 3 ] |> Seq.unfold (fun lst -> 
  match lst with
  | x::xs -> Some(lst, xs)
  | [] -> None
  )

which yields

  seq [[1; 2; 3]; [2; 3]; [3]]

I tried to write the same with seq/yield, but failed... Is this possible? Any other nice ways to write this function?

Upvotes: 0

Views: 187

Answers (1)

Daniel
Daniel

Reputation: 47904

let rec seqOfLists lst =
    seq {
        match lst with
        | _::xs -> 
            yield lst
            yield! seqOfLists xs
        | [] -> ()
    }

Upvotes: 5

Related Questions