Last active
December 27, 2015 16:09
-
-
Save liammclennan/7352790 to your computer and use it in GitHub Desktop.
string calculator
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
let lToS (l:char list) = System.String.Concat(Array.ofList(l)) | |
let sumString = | |
let parse (l:string) = | |
let guessDelimeter (l:string) = | |
match Seq.toList l with | |
| '/'::'/'::c::'\n'::_ -> c | |
| _ -> Seq.find (fun i -> i = ',' || i = '\n') l | |
let valuePart = (fun (s:string) -> | |
match Seq.toList s with | |
| '/'::'/'::c::'\n'::r -> r | |
| v -> v) >> lToS | |
Array.map int ((valuePart l).Split(guessDelimeter l)) | |
(parse >> Array.fold (fun acc i -> acc + i ) 0) | |
sumString "3,9,11" |> printfn "%d" | |
sumString "3\n9\n11" |> printfn "%d" | |
sumString "//;\n3;9;11" |> printfn "%d" |
Thanks Dave. I learned two things:
- String(Array.ofList rest) - didn't know about String
- Array.fold (+) 0 - obvious in hindsight :P
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Some minor refactoring:
Not sure it's worth the conversion to
char list
to use pattern matching.Parser combinators are more fun. :)
Disclaimer: F# newbie