【发布时间】: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#