开发者

Parsing delimiter-separated values in F#

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?


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].


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...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜