Home
Insert
Update snippet 'Recursive active pattern for expanding list quotations'
Title
Description
This is a recursive active pattern for extracting the elements of a list quotation as a list of Exprs, There doesn't seem to be a List pattern in the standard library. The compiler will complain about this recursive pattern unless you use #nowarn "40".
Source code
open FSharp.Reflection open FSharp.Quotations open FSharp.Quotations.Patterns let rec (|List|_|) = let isListType (u:UnionCaseInfo) = u.DeclaringType.IsGenericType && u.DeclaringType.GetGenericTypeDefinition() = typedefof<list<_>> function | NewUnionCase(uci, []) when isListType uci -> Some [] | NewUnionCase(uci, lhs::(NewUnionCase(_, []))::[]) when isListType uci -> Some (lhs::[]) | NewUnionCase(uci, lhs::List(rhs)::[]) when isListType uci -> Some (lhs::rhs) | _ -> None // Usage match <@[5.;6.;7.;8.]@> with | List e -> printf "%A" e | _ -> () match <@[[5.;6.;7.];[8.]]@> with | List e -> e |> List.map (function |List ee-> printf "%A" ee | _ ->()) | _ -> []
Tags
#active patterns
list
quotations
#active patterns
list
quotations
Author
Link
Reference NuGet packages
If your snippet has external dependencies, enter the names of NuGet packages to reference, separated by a comma (
#r
directives are not required).
Update