I have a situation where I'm generating a URL based on a set of query string parameters for use in an API. I know ahead of time that the values passed to this function are URL-safe and the tuples are complete, so I don't need to serialize the data or do data validation beyond just checking the length of the array.
This is a function where I'm generating a url from a (string * string)[]
. I'm trying to avoid using mutable values, so this uses a tail-recursive function to build the string, with the URL being the "accumulator" value for the tail-recursion.
What I'm looking for is ways to better organize the function, flaws in the logic of the workflow, ways to make the function more readable, and just improvements in general.
let ComposeUrl (valuePairs:(string * string)[]) =
let Composer (valuePairs:(string * string)[]) =
let rec ComposerRec (valuePairs:(string * string)[]) (url:string) =
match valuePairs.Length > 0 with
| false -> url
| true ->
let tail = valuePairs.[1..valuePairs.Length - 1]
let url = url + sprintf "&%s=%s" (fst valuePairs.[0]) (snd valuePairs.[0])
ComposerRec tail url
let tail = valuePairs.[1..valuePairs.Length - 1]
let url = sprintf "?%s=%s" (fst valuePairs.[0]) (snd valuePairs.[0])
ComposerRec tail url
match valuePairs.Length > 0 with
| false -> "" // No query string parameters
| true -> Composer valuePairs
match
on a boolean value instead of the much simplerif
? You're not the first person I've seen who does that and I don't understand why do people do it. \$\endgroup\$match
is actually much easier for me to read. I used to useif
if I just had a bool that I was testing against, but after becoming accustomed to usingmatch
for more complicated expressions, I decided to simplify my code by just usingmatch
everywhere. \$\endgroup\$if then else
, like in your code, not more complicated situations. \$\endgroup\$let x = if condition then 42
won't compile; you can't just forgetelse
. \$\endgroup\$