Sha256: 14aa4ca22835f322d2d88dc665337987ae39f6b6f8db9162052206e83422875e

Contents?: true

Size: 1.37 KB

Versions: 79

Compression:

Stored size: 1.37 KB

Contents

module Wordy

open System.Text.RegularExpressions

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

let equationRegex = 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 answer (question: string): int option =  
    question 
    |> parse 
    |> Option.map calculate

Version data entries

79 entries across 79 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.179 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.178 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.177 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.176 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.175 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.174 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.173 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.172 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.171 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.170 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.169 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.167 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.166 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.165 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.164 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.163 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.162 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.161 tracks/fsharp/exercises/wordy/Example.fs
trackler-2.2.1.160 tracks/fsharp/exercises/wordy/Example.fs