Skip to content

Type safe Scanf

cannorin edited this page Apr 19, 2019 · 6 revisions

Module: FSharp.Scanf

Source: src/FSharp.Scanf/scanf.fs


FSharp.Scanf provides several functions to parse string into typed objects type-safely.

FSharp.Scanf is available as a separate package:

PM> Install-Package FSharp.Scanf

open FSharp.Scanf

let (idNum, name, isDead) = scanfn "#%d: %s (dead:%b)"
// input: "#1991: James Brown (dead:true)"
// val name : string = "James Brown"
// val idNum : int = 1991
// val isDead : bool = true

Optimized version

The FSharp.Scanf.Optimized contains the optimized version of the functions above.

They can only work with up to 7 captures (= the return type must be 7-tuples or less), but they don't use reflections under the hood and will run about 6x-7x faster than the normal ones.

To use them, simply open FSharp.Scanf.Optimized instead of FSharp.Scanf. They have the same signature, except the optimized ones have SRTPs in their type parameters.

Functions

  • tryFoo variants return Ok result when it successfully parses the input, or Error exception otherwise.
  • kFoo variants take a continuation to modify the result after parsing.
  • tryKfoo variants do the both.

Reads a line from console

  • scanfn: PrintfFormat<..> -> 'a

  • tryScanfn: PrintfFormat<..> -> Result<'a, exn>

  • kscanfn: PrintfFormat<..> -> ('a -> 'b) -> 'b

  • tryKscanfn: PrintfFormat<..> -> ('a -> 'b) -> Result<'b, exn>

Parses string value

  • sscanf: PrintfFormat<..> -> string -> 'a
  • trySscanf: PrintfFormat<..> -> string -> Result<'a, exn>
  • ksscanf: PrintfFormat<..> -> ('a -> 'b) -> string -> 'b
  • tryKsscanf: PrintfFormat<..> -> ('a -> 'b) -> string -> Result<'b, exn>

Reads a line from TextReader

  • fscanfn: PrintfFormat<..> -> TextReader -> 'a
  • tryFscanfn: PrintfFormat<..> -> TextReader -> Result<'a, exn>
  • kfscanfn: PrintfFormat<..> -> ('a -> 'b) -> TextReader -> 'b
  • tryKfscanfn: PrintfFormat<..> -> ('a -> 'b) -> TextReader -> Result<'b, exn>

Active pattern

function
  | Sscanf "%i-%b" (num, flag) -> ...

Clone this wiki locally