I’ve made the following F# function that will get me an url from the html contents of a web page:
let getPicUrl (urlContents : string) =
let START_TOKEN = "jpg_url="
let startIndex = urlContents.IndexOf(START_TOKEN)
let endIndex = urlContents.IndexOf("&", startIndex)
let s = startIndex + START_TOKEN.Length
let l = endIndex-startIndex-START_TOKEN.Length
urlContents.Substring(s, l)
what the last line, urlContents.Substring(s, l), actually needs is only s and l, so I was wondering whether I could refactor parts of this function into some internal functions so I’d let my intentions be clearer. Ideally getPicUrl would only have 2 let instructions, s and l, and all the others would be internal definitions to those let instructions. If this can in any way be achieved or not is another story..
The only obvious way I can think at the moment to improve the above code would be to switch endIndex of place so we’d have
let getPicUrl (urlContents : string) =
let START_TOKEN = "jpg_url="
let startIndex = urlContents.IndexOf(START_TOKEN)
let s = startIndex + START_TOKEN.Length
let l =
let endIndex = urlContents.IndexOf("&", startIndex)
endIndex-startIndex-START_TOKEN.Length
urlContents.Substring(s, l)
but I keep wondering if there’d be a clearer way of organizing this function’s let definitions.
Firstly, your function is buggy. A non-matching string will make it grumpy.
I like regexes for this sort of thing. With this active pattern:
you can do:
You could also turn your original approach into an active pattern:
and do: