So I love it when a very natural use case arises for a feature that I want to practice. I’ve been trying to better my understanding of active patterns lately and today I found a great use for them.
I’m fetching json data from a REST endpoint. Of course I get back a string. And the string contains some very specific text when there’s a problem processing the request on the server side. So I ended up doing something like this:
let errResult = "Error creating user" let (|ContainsErrString|) (stringToTest:String) = stringToTest.Contains(errResult) //And further down in the code: let res = sr.ReadToEnd() let u1 = match res with | ContainsErrString true -> None | _ -> Some(JsonConvert.DeserializeObject<user>(res))
Simplifies the code dramatically and hides detail that the match doesn’t need to know about. Terrific use case for an active pattern.