解析f#中的分隔仪分离值

发布于 2024-12-05 06:53:35 字数 329 浏览 1 评论 0原文

我正在以此形式解析字符串记录:

description: double/double/double

对于Ex。:

item description: 0.4/8/-24.66

每个记录都应导致一个对象:

new MyObj("first item", 0.4, 2.4, -24.66)

我可以通过正则表达式和程序方法轻松地执行此操作,但是结果代码容易出错,却相当丑陋(至少来自功能的观点)。

如何以更优雅的方式完成这件事?

I am parsing string records in this form:

description: double/double/double

for ex.:

item description: 0.4/8/-24.66

Each record should result in an object:

new MyObj("first item", 0.4, 2.4, -24.66)

I could easily do this with a regular expression and a procedural approach, but the resulting code is error-prone and rather ugly (at least from a functional point of view).

How can this be accomplished in a more elegant way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小巷里的女流氓 2024-12-12 06:53:35

嗯,FParsec 很好:

#r "FParsecCS.dll"
#r "FParsec.dll"

open FParsec

let parser : Parser<_,unit> =
    sepBy pfloat (pchar '/')

然后 run parser "0.4/8/-24.66" 返回 val it : ParserResult; = 成功:[0.4; 8.0; -24.66]

Well, FParsec is nice:

#r "FParsecCS.dll"
#r "FParsec.dll"

open FParsec

let parser : Parser<_,unit> =
    sepBy pfloat (pchar '/')

And then run parser "0.4/8/-24.66" returns val it : ParserResult<float list,unit> = Success: [0.4; 8.0; -24.66].

嘦怹 2024-12-12 06:53:35

或者,您只需创建一个简单的解析器函数string-&gt; myobj像这样:(

type MyObj(descr:string, a:float, b:float, c:float) =
    override this.ToString() =
        System.String.Format("{0}: {1}; {2}; {3}", descr,a,b,c)

let myobjfromstr (str:string) = 
    let flds = str.Split([|':';'/'|])
    let ip s = System.Double.Parse(s)    
    new MyObj(flds.[0], ip flds.[1], ip flds.[2], ip flds.[3])

myobjfromstr "item description: 0.4/8/-24.66" |> printfn "%A"

update:我猜想记录是由新线或类似的东西隔开的被分为第二个想法。

Or you can just create a simple parser function string->MyObj like this:

type MyObj(descr:string, a:float, b:float, c:float) =
    override this.ToString() =
        System.String.Format("{0}: {1}; {2}; {3}", descr,a,b,c)

let myobjfromstr (str:string) = 
    let flds = str.Split([|':';'/'|])
    let ip s = System.Double.Parse(s)    
    new MyObj(flds.[0], ip flds.[1], ip flds.[2], ip flds.[3])

myobjfromstr "item description: 0.4/8/-24.66" |> printfn "%A"

(update: I guessed that records were separated by a new-line or something like that and were split into a list. On the second thought, there's nothing like that in your question...)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文