F# Active Pattern List.filter or equivalent

Posted by akaphenom on Stack Overflow See other posts from Stack Overflow or by akaphenom
Published on 2010-04-19T23:04:22Z Indexed on 2010/04/19 23:43 UTC
Read the original article Hit count: 443

Filed under:
|
|

I have a records of types

type tradeLeg = {
    id : int ;
    tradeId : int ;
    legActivity : LegActivityType ;
    actedOn : DateTime ;
    estimates : legComponents ;
    entryType : ShareOrDollarBased ;
    confirmedPrice: DollarsPerShare option;
    actuals : legComponents option ; 


type trade = {
    id : int ;
    securityId : int ;
    ricCode : string ;
    tradeActivity : TradeType ;
    enteredOn : DateTime ;
    closedOn : DateTime ;
    tradeLegs : tradeLeg list  ;
}

Obviously the tradeLegs are a type off of a trade. A leg may be settled or unsettled (or unsettled but price confirmed) - thus I have defined the active pattern:

let (|LegIsSettled|LegIsConfirmed|LegIsUnsettled|) (l: tradeLeg) = 
        if Helper.exists l.actuals then LegIsSettled
        elif Helper.exists l.confirmedPrice then LegIsConfirmed
        else LegIsUnsettled

and then to determine if a trade is settled (based on all legs matching LegIsSettled pattern:

let (|TradeIsSettled|TradeIsUnsettled|) (t: trade) = 
        if List.exists (
            fun l -> 
                match l with 
                    | LegIsSettled -> false 
                    | _ -> true) t.tradeLegs then TradeIsSettled
        else TradeIsUnsettled

I can see some advantages of this use of active patterns, however i would think there is a more efficient way to see if any item of a list either matches (or doesn't) an actie pattern without having to write a lambda expression specifically for it, and using List.exist.

Question is two fold:

  1. is there a more concise way to express this?
  2. is there a way to abstract the functionality / expression

    (fun l -> match l with | LegIsSettled -> false | _ -> true)

Such that

let itemMatchesPattern pattern item  =
    match item with
         | pattern -> true
         | _ -> false

such I could write (as I am reusing this design-pattern):

let curriedItemMatchesPattern = itemMatchesPattern LegIsSettled
if List.exists curriedItemMatchesPattern t.tradeLegs then TradeIsSettled
        else TradeIsUnsettled

Thoughts?

© Stack Overflow or respective owner

Related posts about F#

Related posts about active-pattern