如何将用英语单词编写的数字解析为F#中的数字等价物?

时间:2013-10-31 12:30:15

标签: .net recursion f# functional-programming

F#中最简单的方法(在函数/递归样式中),给定一个单词中的数字,将其转换为数字等价物?

我现在只看英语。 E.g:

let parseNumber (s : string) =
    match s with
    | "One" -> 1
    | _ - failwith "Cannot parse"

let result = parseNumber "One Thousand Two Hundred"
// result should be 12000

有没有办法做到这一点,不涉及大量的查询表?

1 个答案:

答案 0 :(得分:7)

这是一个天真/简单的解决方案,但你需要扩展它以支持所有数字(例如“三万”):

open System

let parseNumber (s : string) =
    let parts = s.Split ' ' |> Array.rev |> Array.toList
    let rec parseParts (s : string list) =
        match s with
        | [] -> 0
        | "One" :: rest -> 1 + parseParts rest
        | "Two" :: rest -> 2 + parseParts rest
        | "Three" :: rest -> 3 + parseParts rest
        | "Four" :: rest -> 4 + parseParts rest
        | "Five" :: rest -> 5 + parseParts rest
        | "Six" :: rest -> 6 + parseParts rest
        | "Seven" :: rest -> 7 + parseParts rest
        | "Eight" :: rest -> 8 + parseParts rest
        | "Nine" :: rest -> 9 + parseParts rest
        | "Ten" :: rest -> 10 + parseParts rest
        | "Hundred" :: t :: rest -> parseParts [t] * 100 + parseParts rest
        | "Thousand" :: t :: rest -> parseParts [t] * 1000 + parseParts rest
        | _ -> failwith "Ug"
    parseParts parts

parseNumber "One" |> printfn "%i"
parseNumber "Two Hundred" |> printfn "%i"
parseNumber "Three Thousand" |> printfn "%i"
parseNumber "Three Thousand Four" |> printfn "%i"
parseNumber "One Thousand Two Hundred" |> printfn "%i"