我正在努力创建一个F#函数。我是F#的新手(充其量)并且真的可以使用一些帮助。我已经倾倒了一个星期,所以你能提供的任何帮助都是非常宝贵的!
功能目标:
List
和string
Proper Case
示例:
功能操作:
这就是我到目前为止所做的。
let myList = ["NIF"; "PF"; "PS"; "SC"; "US"; "USA"; "USD"]
let FixAccronyms aList fixString=
aList |> List.iter
(fun listItem ->
match listItem with
| fixString -> printfn "%s, %s" listItem fixString
| _ -> printf "%s" "" |> ignore)
在FSI:
FixAccronyms myList“美元在sc中”;;
该函数遍历列表,但它会打印列表中的每个项目,而不仅仅是它与fixString匹配的位置。假设有效,我既不确定如何模式匹配字符串的一部分,也不确定字符串中的查找和替换......
FSI的结果
val myList2 : string list = ["NIF"; "PF"; "PS"; "SC"; "US"; "USA"; "USD"]
val FixAccronyms2 : aList:string list -> fixString:'a -> unit
>FixAccronyms2 myList2 "the us dollar in sc";;
NIF, NIF
PF, PF
PS, PS
SC, SC
US, US
USA, USA
USD, USD
val it : unit = ()
提前谢谢!
答案 0 :(得分:1)
以这种方式:
open System
open System.Collections.Generic
let properCase lookup (str: string) =
let lookupDict = Dictionary(StringComparer.CurrentCultureIgnoreCase)
for word in lookup do lookupDict.Add(word, word)
(str, str.Split()) ||> Array.fold (fun pcWord word ->
match lookupDict.TryGetValue(word) with
| true, s -> pcWord.Replace(word, s)
| _ -> pcWord)
> properCase ["NIF"; "PF"; "PS"; "SC"; "US"; "USA"; "USD"] "The us dollar in sc"
val it : string = "The US dollar in SC"
答案 1 :(得分:1)
这是另一种方法:
open System
open System.Text.RegularExpressions
let properCase lookup str =
Regex.Replace(str, String.Join("|", Seq.map Regex.Escape lookup),
(fun (x : Match) -> x.Value.ToUpper()),
RegexOptions.IgnoreCase)
用法与@ Daniel的答案相同。