2017-02-11 48 views
2

在我的代碼showen下面我試圖改變第一個字符串的第一個字母爲大寫並設置一個問號:F# - 大寫的第一個字符串列表中

let strList = ["are"; "you"; "hungry"] 

let rec add l = match l with 
       |[] -> ["?"] 
       |x::xs -> x::(add xs) 

add strList 

,我設法解決在最後的問號,讓這個列表回:

["are"; "you"; "hungry"; "?"] 

有沒有對如何在遞歸函數addare的第一個字母改爲Are任何想法?

回答

4

您可以添加該應用正確的改造,輸入列表中的第一個元素並調用您已經擁有其餘元素遞歸函數一個新的功能:

open System 

let strList = ["are"; "you"; "hungry"] 

let add l = 
    let rec add l = 
    match l with 
    | [] -> ["?"] 
    | x::xs -> x::(add xs) 

    let upper (s: string) = 
    s |> Seq.mapi (fun i c -> match i with | 0 -> (Char.ToUpper(c)) | _ -> c) |> String.Concat 

    match l with 
    | [] -> add l 
    | x :: xs -> (upper x) :: (add xs) 

add strList 

和輸出是一樣你會期望它:

val strList : string list = ["are"; "you"; "hungry"] 
val add : l:string list -> string list 
val it : string list = ["Are"; "you"; "hungry"; "?"] 
+4

有一個內置的方法來大寫單詞。讓toTitleCase = System.Globalization.CultureInfo.InvariantCulture.TextInfo.ToTitleCase – Wally

相關問題