unj2
unj2

Reputation: 53491

How do I use function parameter as literal for pattern matching in F#?

How do I write a match function that takes two strings and compares them with each other? Right now I just have this. The first one does not work. Is there a better way?

let matchFn ([<Literal>]matchString) (aString : string) = match aString with
                                                            matchString -> true
                                                            | _ -> false

let matchFn (matchString : string) (aString : string) = match aString with
                                                          _ when (matchString = aString) -> true
                                                          | _ -> false

Upvotes: 0

Views: 516

Answers (2)

brianary
brianary

Reputation: 9322

You can use a guarded match:

let matchFn matchString (aString : string) = match aString with
                                                 x when x = matchString -> true
                                                 | _ -> false

or, perhaps more idiomatically:

let matchFn (matchString:string) = function
    | x when x = matchString -> true
    | _ -> false

Upvotes: 1

wmeyer
wmeyer

Reputation: 3496

In this specific case, you could of course just write aString = matchString, but I suppose you are asking about the general case. Literals are allowed only on the module level, and they must have a simple constant expression on their right side (source).

However, you can use an active pattern for cases like this. For example (from here):

let (|Equals|_|) expected actual = 
  if actual = expected then Some() else None

and then use it like this:

let matchFn (matchString : string) (aString : string) =
   match aString with
   | Equals matchString -> true
   | _ -> false

Upvotes: 4

Related Questions