Last active
June 17, 2020 23:16
-
-
Save Szer/acc467571a0b013a0efe70c76cf5f149 to your computer and use it in GitHub Desktop.
Pattern matching for all sequences
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open System | |
[<RequireQualifiedAccess>] | |
module Seq = | |
let inline (|Nil|Cons|) (someSeq: seq<_>) = | |
let mutable enum = Unchecked.defaultof<IEnumerator<_>> | |
let mutable shouldDispose = true | |
try | |
enum <- someSeq.GetEnumerator() | |
if enum.MoveNext() then | |
let head = enum.Current | |
shouldDispose <- false | |
let rest = seq { | |
use localEnum = enum | |
while localEnum.MoveNext() do | |
yield localEnum.Current | |
} | |
Cons(head, rest) | |
else | |
Nil | |
finally | |
if shouldDispose && not(isNull enum) then | |
(enum :> IDisposable).Dispose() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please ensure these samples properly work (
finally
should always execute):