Skip to content

Instantly share code, notes, and snippets.

@bleis-tift
Last active August 29, 2015 14:08
Show Gist options
  • Save bleis-tift/cd07be367a6860c97c6b to your computer and use it in GitHub Desktop.
Save bleis-tift/cd07be367a6860c97c6b to your computer and use it in GitHub Desktop.
open FParsec
open FParsec.CharParsers
let toInt ch = (int ch) - (int '0')
let parser = parse {
let! head = digit |>> toInt
do! digit |>> ignore
do! digit |>> ignore
do! digit |>> ignore
do! digit |>> ignore
let! sixth = digit |>> toInt
match head with
| 8 | 9 ->
if 1 <= sixth && sixth <= 5 then
return (head, sixth)
else
return! fail "oops!"
| _ ->
return (head, sixth)
}
let tryParse str =
match run (parser .>> eof) str with
| Success (res, _, _) -> Some res
| Failure _ -> None
let validate str =
match tryParse str with
| Some x -> printfn "valid! %A" x
| None -> printfn "invalid..."
[<EntryPoint>]
let main argv =
validate "923451" // ok
validate "923455" // ok
validate "923456" // ng
validate "123456" // ok
0
// 別解:アクティブパターンで
let (|Head|) (str: string) = str.[0] |> string |> int
let (|Sixth|) (str: string) = str.[5] |> string |> int
let validate str =
match str with
| Head head when head = 8 || head = 9 ->
match str with
| Sixth sixth when 1 <= sixth && sixth <= 5 ->
printfn "valid! %A" (head, sixth)
| _ ->
printfn "invalid..."
| Head head ->
printfn "valid! %A" (head, str.[5] |> string |> int)
[<EntryPoint>]
let main argv =
validate "923451" // ok
validate "923455" // ok
validate "923456" // ng
validate "123456" // ok
0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment