重构 F# 小函数
我创建了以下 F# 函数,它将从网页的 html 内容中获取 url:
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)
最后一行 urlContents.Substring(s, l)
实际需要的只是 s
和 l
,所以我想知道是否可以将此函数的部分内容重构为一些内部函数,以便我的意图更加清晰。理想情况下,getPicUrl
只会有 2 个 let
指令,s
和 l
,所有其他指令都是内部定义这些 let
指令。如果这能以任何方式实现,那就是另一个故事了。
目前我能想到的改进上述代码的唯一明显的方法是切换位置的 endIndex
,这样我们就可以了,
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)
但是我一直想知道是否有一种更清晰的方法来组织这个函数的 let
定义。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,你的功能有问题。不匹配的字符串会让它变得脾气暴躁。
我喜欢用正则表达式来处理这类事情。使用此活动模式:
您可以执行以下操作:
您还可以将原始方法转变为活动模式:
并执行以下操作:
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:
你可以这样写:
You can write it this way:
另一种选择是使用字符串的 split 方法(我希望字符串不要太长,否则会影响性能)并使用选项类型来指示是否找到 URL。
Another option would be to use split method of string (I hope the string is not too long as that would be a performance hit) and use option type to indicate whether the URL was found or not.