Is there a way to not repeat this function call when matching with a pattern?

I have a string for which I want to use the active template for matching. I noticed that I need to repeat the same function call when the value is the input to the function. Is there a way to not continue calling the function?

let (|A|B|C|X|) stringValue = match stringValue with | value when compareCaseInsensitive stringValue "a" -> A | value when compareCaseInsensitive stringValue "b" -> B | value when compareCaseInsensitive stringValue "c" -> C | _ -> X stringValue 
+5
source share
4 answers

You can define another active template for the black box function:

 let (|CCI|_|) (v: string) c = if v.Equals(c, System.StringComparison.InvariantCultureIgnoreCase) then Some() else None let (|A|B|C|X|) stringValue = match stringValue with | CCI "a" -> A | CCI "b" -> B | CCI "c" -> C | _ -> X stringValue 
+10
source

It seems you are trying to force pattern matching where it does not always fit. A good indicator that you are trying to force pattern matching is a lot of conditional checks in your pattern (in this case, you are not actually performing pattern matching!).

 let (|A|B|C|X|) stringValue = let compareValue = compareCaseInsensitive stringValue if compareValue "a" then A elif compareValue "b" then B elif compareValue "c" then C else X stringValue 
+5
source

For this problem, I would use the answer suggested by mydogisbox, but if this question is a backup for a more complex real problem or there is some other reason why you should use pattern matching, you can do something like this:

 let (|A|B|C|X|) stringValue = let compare x = compareCaseInsensitive stringValue x match List.map compare ["a"; "b"; "c"] with | [true; _; _] -> A | [_; true; _] -> B | [_; _; true] -> C | _ -> X stringValue 

This is definitely not the method that I would use in the case of a question posted , but perhaps it can inspire a solution if there is a more complex underlying problem.

+5
source
 let (|A|B|C|X|) (stringValue: string) = match stringValue.ToLower() with // or your custom toLowerCase function | "a" -> A | "b" -> B | "c" -> C | _ -> X stringValue 
+4
source

Source: https://habr.com/ru/post/1234278/


All Articles