F# - 大写列表中的第一个字符串

时间:2017-02-11 21:42:59

标签: f# functional-programming

在我下面的代码中,我试图将第一个字符串的第一个字母更改为大写,并设置一个问号:

template<typename T>
class D:
{
    D(const T* t): m_t(t) {};
    int doThat(void) { return m_t->num(); };

private:
    T* m_t;
}

A ar[2] = { A(1), A(2) };
B l(ar, 2);
C<B> j(&l);

我设法在最后修复问号,并将此列表取回:

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

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

add strList

关于如何在递归函数["are"; "you"; "hungry"; "?"] 中将are中的第一个字母更改为Are,是否有任何想法?

1 个答案:

答案 0 :(得分: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"; "?"]