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

标签 f# functional-programming

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

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

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

add strList

我设法修复了最后的问号并取回了此列表:

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

是否有关于如何在递归函数 add 中将 are 中的第一个字母更改为 Are 的想法?

最佳答案

您可以添加一个新函数,它将正确的转换应用于输入列表中的第一个元素,并调用您已有的其余元素的递归函数:

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"; "?"]

关于F# - 将列表中的第一个字符串大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42181578/

相关文章:

F# 将字符串拆分为元组的最简单方法

F#,使用map2和map3定义map4的简洁方法

c - 如何将数组从 .Net 传递到 C?

f# - 在 FSharp 中键入同义词

authentication - 如何向 Scotty 中间件添加基本身份验证?

swift - 在 Swift 中使用 reduce() 构建字典

java - Python/函数式小白,将不可读的Java递归转换为Python

functional-programming - 方案中的 eq?、eqv?、equal? 和 = 有什么区别?

database - 健忘症患者的 "first"功能语言? (我真的很喜欢 Clojure...)

f# - 数学序列进一步的元素