Essay - Published: 2024.05.29 | create | fsharp | tech |
DISCLOSURE: If you buy through affiliate links, I may earn a small commission. (disclosures)
In webdev there's a lot of raw string to value conversion. This is because, like it or not, most network communication is done via raw strings. To be able to leverage the power of F#'s type system, we need to safely convert these into the type our domain expects and handle errors if and when they occur.
In this post we'll explore a simple method for safely parsing an int from a raw string in F#.
For this example we'll be using the built-in Int32.TryParse method. I like this for a few reasons:
You can use the function directly but I like to wrap it in an option because I think it pipelines a little better.
Code:
let tryParseInt
(s: string)
: int option
=
let success, result = Int32.TryParse s
match success with
| true -> Some result
| false -> None
You can try it out in this example Replit.
There are probably many other ways to do this, each with their own pros / cons.
Some popular ones can make this conversion easier if you know for a fact that your string is parseable to an int. I would argue that if you have a string you cannot know for sure that it is int parseable so you should just use the error-safe method but to each their own.
Some alternative ways to convert that will fail hard (throw) if not int parseable:
s |> int - uses built-in int function to convert string to intInt32.Parse - Same API we used above just converts directly or fails hardThere are infinite ways to do any one thing - this is just a method I've found works well.
Q: How are you doing type conversions in F#?
If you liked this post you might also like:
The best way to support my work is to like / comment / share for the algorithm and subscribe for future updates.