Skip to content

Instantly share code, notes, and snippets.

@einarwh
Last active August 29, 2015 14:21
Show Gist options
  • Save einarwh/31c9a5a99dce673e7dc1 to your computer and use it in GitHub Desktop.
Save einarwh/31c9a5a99dce673e7dc1 to your computer and use it in GitHub Desktop.
1-9 to 100 with FParsec
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