什么是 F # 中最简单的方法(在功能 / 递归风格),给定一个数字的话,将其转换为它的数字等效?
我现在只看英语。例如:
let pNumber (s : string) =
match s with
| "One" -> 1
| _ - failwith "Cannot p"
let result = pNumber "One Thousand Two Hundred"
// result should be 12000
有没有办法做到这一点,不涉及一个巨大的查找表?
这是一个天真的 / 简单的解决方案,但你需要扩展它以支持所有数字(例如“三万”):
open System
let pNumber (s : string) =
let parts = s.Split ' ' |> Array.rev |> Array.toList
let rec pParts (s : string list) =
match s with
| [] -> 0
| "One" :: rest -> 1 + pParts rest
| "Two" :: rest -> 2 + pParts rest
| "Three" :: rest -> 3 + pParts rest
| "Four" :: rest -> 4 + pParts rest
| "Five" :: rest -> 5 + pParts rest
| "Six" :: rest -> 6 + pParts rest
| "Seven" :: rest -> 7 + pParts rest
| "Eight" :: rest -> 8 + pParts rest
| "Nine" :: rest -> 9 + pParts rest
| "Ten" :: rest -> 10 + pParts rest
| "Hundred" :: t :: rest -> pParts [t] * 100 + pParts rest
| "Thousand" :: t :: rest -> pParts [t] * 1000 + pParts rest
| _ -> failwith "Ug"
pParts parts
pNumber "One" |> printfn "%i"
pNumber "Two Hundred" |> printfn "%i"
pNumber "Three Thousand" |> printfn "%i"
pNumber "Three Thousand Four" |> printfn "%i"
pNumber "One Thousand Two Hundred" |> printfn "%i"
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(85条)