f# 中字符串开头的模式匹配
我正在尝试匹配 f# 中字符串的开头。不确定我是否必须将它们视为字符列表或什么。任何建议将不胜感激。
这是我想要做的伪代码版本
let text = "The brown fox.."
match text with
| "The"::_ -> true
| "If"::_ -> true
| _ -> false
所以,我想查看字符串的开头并进行匹配。请注意,我没有匹配字符串列表,只是将上面的内容写为我想要做的事情的本质的想法。
I am trying to match the beginning of strings in f#. Not sure if I have to treat them as a list of characters or what. Any suggestions would be appreciated.
Here is a psuedo code version of what I am trying to do
let text = "The brown fox.."
match text with
| "The"::_ -> true
| "If"::_ -> true
| _ -> false
So, I want to look at the beginning of the string and match. Note I am not matching on a list of strings just wrote the above as an idea of the essence of what I am trying to do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
参数化活动模式来救援!
Parameterized active patterns to the rescue!
您还可以在模式上使用防护:
You could also use a guard on the pattern:
是的,如果您想使用匹配表达式,则必须将它们视为字符列表。
只需将字符串转换为:
然后您可以使用匹配表达式,但您必须为每个字母使用字符(列表中元素的类型):
正如 Brian 建议的那样,参数化活动模式要好得多,有一些有用的模式 此处(转到页面末尾)。
Yes you have to treat them as a list of characters if you want to use a match expression.
Simply transform the string with:
Then you can use a match expression but you will have to use chars (the type of elements in the list) for each letter:
As Brian suggest Parameterized Active Patterns are much nicer, there a some useful patterns here (go the end of the page).