开发者

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

开发者 https://www.devze.com 2023-02-17 18:31 出处:网络
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?

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) -> 开发者_C百科true
                                                          | _ -> false


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号