2 people like it.

Parsing formulas

Parsing simple formulas using active patterns

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
open System

let (|ParseNumber|_|) text = 
  match Int32.TryParse(text) with
  | true, num -> Some(sprintf "Number: %d" num)
  | _ -> None

let (|ParseExpression|_|) (text:string) = 
  if text.StartsWith("=") then 
    Some(sprintf "Formula: %s" (text.Substring(1)))
  else 
    None

let (|Length|) (text:string) = 
  text.Length

let parseFormula text =
  match text with
  | Length 0 -> "Empty"
  | ParseNumber s -> s
  | ParseExpression s -> s
  | _ -> "Error"

parseFormula "" 
parseFormula "= 4 + 3"
parseFormula "42"
parseFormula "error"
namespace System
val text : string
type Int32 =
  struct
    member CompareTo : value:obj -> int + 1 overload
    member Equals : obj:obj -> bool + 1 overload
    member GetHashCode : unit -> int
    member GetTypeCode : unit -> TypeCode
    member ToString : unit -> string + 3 overloads
    static val MaxValue : int
    static val MinValue : int
    static member Parse : s:string -> int + 3 overloads
    static member TryParse : s:string * result:int -> bool + 1 overload
  end

Full name: System.Int32
Int32.TryParse(s: string, result: byref<int>) : bool
Int32.TryParse(s: string, style: Globalization.NumberStyles, provider: IFormatProvider, result: byref<int>) : bool
val num : int
union case Option.Some: Value: 'T -> Option<'T>
val sprintf : format:Printf.StringFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.sprintf
union case Option.None: Option<'T>
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = String

Full name: Microsoft.FSharp.Core.string
String.StartsWith(value: string) : bool
String.StartsWith(value: string, comparisonType: StringComparison) : bool
String.StartsWith(value: string, ignoreCase: bool, culture: Globalization.CultureInfo) : bool
String.Substring(startIndex: int) : string
String.Substring(startIndex: int, length: int) : string
property String.Length: int
val parseFormula : text:string -> string

Full name: Script.parseFormula
active recognizer Length: string -> int

Full name: Script.( |Length| )
active recognizer ParseNumber: string -> string option

Full name: Script.( |ParseNumber|_| )
val s : string
active recognizer ParseExpression: string -> string option

Full name: Script.( |ParseExpression|_| )
Raw view New version

More information

Link:http://fssnip.net/ib
Posted:3 years ago
Author:Tomas Petricek
Tags: active pattern , formula