Project Euler 22

http://projecteuler.net/index.php?section=problems&id=22


Fileの入力には.NETを使います。

open System
open System.IO

let rec split (str : string) p1 p2 mode =
   if p2 = str.Length then
      []
   else if mode = 0 then
      if str.[p2] = '"' then
         split str (p2 + 1) (p2 + 1) 1
      else
         split str p1 (p2 + 1) 0
   else
      if str.[p2] = '"' then
         str.[p1..p2-1] :: (split str p1 (p2 + 1) 0)
      else
         split str p1 (p2 + 1) 1

let read_names () =
   let s = new StreamReader("names.txt")
   let str = s.ReadLine()
   s.Close ()
   List.sort (split str 0 0 0)

let count n = Seq.initInfinite (fun k -> k + n)
let char_sum s = List.sum [ for c in s -> (int c) - (int 'A') + 1 ]

printfn "%d" (List.sum [ for n, s in Seq.zip (count 1) (read_names ())
                                                -> n * (char_sum s) ])