Last active
August 29, 2015 14:21
-
-
Save einarwh/31c9a5a99dce673e7dc1 to your computer and use it in GitHub Desktop.
1-9 to 100 with FParsec
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open FParsec | |
let rec permute xs = seq { | |
match xs with | |
| [] -> yield "" | |
| [x] -> yield string x | |
| h::t -> | |
let s = string h | |
for foo in permute t do | |
yield s + foo | |
yield s + "+" + foo | |
yield s + "-" + foo | |
} | |
let eval str = | |
let parse = | |
let pp op = pstring op >>. pint32 | |
let ppos = pp "+" | |
let pneg = pp "-" |>> (fun x -> -x) | |
pipe2 pint32 (many (ppos <|> pneg)) (fun x y -> List.sum (x::y)) | |
match run parse str with | |
| Success(n, _, _) -> n | |
| _ -> 0 | |
let solutions = Seq.filter (fun x -> eval x = 100) | |
[1..9] |> permute |> solutions |> Seq.toList |> printfn "%A" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment