计算给定字符串 F# 中元音的数量
count the number of vowels in a given string F#
我需要一个使用 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() which returns a true/false,如果条件为真,它将向作为 0 参数的累加器加 1。当我尝试在匿名函数中使用 if else 时出现错误。
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"]
您正在尝试折叠列表,但您的源实际上是一个字符串。
如果使用 Seq.fold
:
,则字符串可以解释为字符序列
"abracadabra" |> Seq.fold (fun i c -> if isVowel c then i + 1 else i) 0
// val it : int = 5
这就是我要找的。谢谢格斯!
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
我需要一个使用 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() which returns a true/false,如果条件为真,它将向作为 0 参数的累加器加 1。当我尝试在匿名函数中使用 if else 时出现错误。
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"]
您正在尝试折叠列表,但您的源实际上是一个字符串。
如果使用 Seq.fold
:
"abracadabra" |> Seq.fold (fun i c -> if isVowel c then i + 1 else i) 0
// val it : int = 5
这就是我要找的。谢谢格斯!
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