gpt4 book ai didi

f# - Seq.where 与 Seq.groupBy

转载 作者:行者123 更新时间:2023-12-05 00:24:39 27 4
gpt4 key购买 nike

在学习 F# 时,我正在做一个小挑战:

Enter a string and the program counts the number of vowels in the text. For added complexity have it report a sum of each vowel found.



这是我到目前为止:
let rec Main = 
let vowels = [| 'a'; 'e'; 'i'; 'o'; 'u'|]
let charIsVowel char = Seq.exists ((=) char) vowels

let inputText = Console.ReadLine()

let expression =
inputText
|> Seq.groupBy (fun char -> char)
|> Seq.where charIsVowel

问题是我无法访问分组的 key char所以我无法过滤序列。
具体错误是:

Type mismatch. Expecting a char * seq -> bool
but given a char -> bool
The type 'char * seq' does not match the type 'char'



最终,我想根据它们的键过滤一系列摸索。我怎样才能做到这一点?

最佳答案

您只需要在调用 charIsVowel 之前先将元组拆开即可。 :

Seq.where (fun (char, s) -> charIsVowel char)

另一种方法是使用 fst函数以及函数组合:
Seq.where (fst >> charIsVowel)
fst功能转 (char, s)进入 char然后是 >>运算符将结果传递给 charIsVowel .

请注意您的 (fun char -> char)groupBy可以简单地表示为恒等函数 id :
Seq.groupBy id

关于f# - Seq.where 与 Seq.groupBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25796199/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com