【问题标题】:count the number of vowels in a given string F#计算给定字符串中元音的数量 F#
【发布时间】:2021-06-09 02:25:06
【问题描述】:

我需要一个使用 List.fold 的方法来计算给定字符串中元音的数量。 到目前为止我有这个方法。

let vowels = ['a';'e';'i';'o';'u']
let isVowel =
    fun c -> vowels |> List.contains c

let count =
    String.filter isVowel
    >> String.length

printfn "%A" (count "aaaa")

它工作正常,但我不知道如何使用相同的 isVowel 方法制作 List.fold 。这是我的尝试。

下面的代码不起作用,它的目的是反映我的想法。由于 fold 方法应用了 isVowel() ,它在字符串中的每个字符上返回一个真/假,如果条件为真,它将向累加器加 1,即 0 参数。当我尝试使用 if else insinde anon 函数时,我得到一个错误。

let isVowel x = 
    match x with 
    | 'a' -> true
    | 'e' -> true
    | 'i' -> true
    | 'o' -> true
    | 'u' -> true
    | _ -> false

let countNumOfVowels =
    List.fold (fun (isVowel) (x) -> x + 1) 0 ["aaaa"]

【问题讨论】:

  • 你能说明你是如何在匿名函数中使用 if/else 的吗?
  • let countNumOfVowels = List.fold (fun (isVowel) x -> if isVowel then x + 1 ) 0 [ "aaaa" ] 这对我来说没有意义,但至少我试过))
  • isVowel没有参数,函数没有调用isVowel的char

标签: string count functional-programming f#


【解决方案1】:

这就是我要找的。谢谢格斯!

let countNumOfVowels str =
    List.fold (fun (x: int) (c: char) -> if (isVowel c) then x + 1 else x) 0 (Seq.toList str)

countNumOfVowels "Hello"
> countNumOfVowels "Hello";;
val it : int = 2

【讨论】:

    【解决方案2】:

    您正在尝试折叠列表,但您的源实际上是一个字符串。

    如果使用Seq.fold,则字符串可以解释为字符序列:

    "abracadabra" |> Seq.fold (fun i c -> if isVowel c then i + 1 else i) 0
    
    // val it : int = 5
    

    【讨论】:

    • 我可以将字符串转换成字符序列并在 List.fold 中使用吗?
    • 当然,你可以先发List.ofSeq,然后再发List.fold
    • 请注意,您也可以在 isVowels 函数中使用相同的逻辑,从而简化它。将元音也设为字符串,因此:let isVowels c = Seq.contains c "aeiou"
    猜你喜欢
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多