Sha256: 73079f3ad920100c05853ba4ce67d3dfcc95897d9a44ff3f78be9675e78ef651

Contents?: true

Size: 1.38 KB

Versions: 317

Compression:

Stored size: 1.38 KB

Contents

module Wordy

open System
open System.Text.RegularExpressions

type Operation = int -> int
type Equation = int * (Operation list)

let equationRegex = new Regex(@"(?<left>-?\d+) (?<operation>-?plus|minus|divided by|multiplied by) (?=(?<right>-?\d+))", RegexOptions.Compiled)

let regexGroupStr (group: string) (m: Match) = m.Groups.[group].Value
let regexGroupNumber (group: string) (m: Match) = regexGroupStr group m |> int

let calculate (left, operations) = List.fold (fun acc item -> item acc) left operations

let parseRight (m: Match) = regexGroupNumber "right" m

let parseOperand (m: Match) = 
    match regexGroupStr "operation" m with
    | "plus"          -> (+)
    | "minus"         -> (-)
    | "multiplied by" -> (*)
    | "divided by"    -> (/)
    | _ -> failwith "Unknown operation"

let parseOperation (m: Match) =
    fun x -> (parseOperand m) x (parseRight m)

let parseOperations (matches: MatchCollection) =
    matches 
    |> Seq.cast<Match> 
    |> Seq.map parseOperation
    |> Seq.toList

let parseLeft (matches: MatchCollection) = 
    matches 
    |> Seq.cast 
    |> Seq.head 
    |> regexGroupNumber "left" 

let parse (question: string): Equation option =
    match equationRegex.Matches question with
    | m when m.Count = 0 -> None
    | m -> Some (parseLeft m, parseOperations m)

let solve (question: string): int option =  
    question 
    |> parse 
    |> Option.map calculate

Version data entries

317 entries across 317 versions & 1 rubygems

Version Path
trackler-2.2.1.99 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.98 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.97 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.96 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.95 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.94 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.93 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.92 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.91 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.90 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.89 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.88 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.87 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.86 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.85 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.84 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.83 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.82 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.81 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.80 tracks/fsharp/exercises/wordy/Example.fs