我试图用F#写一个猪拉丁语翻译器。要翻译,我需要知道一个单词是否以元音开头。为此,我试图使用我写的这个函数......
(*Tests if an element is in a list*)
let isInList elementToFind listToCheck =
List.fold(fun a b -> a || b = elementToFind) false listToCheck;
测试单词中的第一个字符是否在所有元音的列表中。以下是我的尝试
(*Takes a word and translates it to pig latin*)
let translateWord wordToTranslate : string =
let startsWithVowel = isInList(wordToTranslate.[0], ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']);
if startsWithVowel then
translateWordStartingWithVowel(wordToTranslate)
else
translateWordStartingWithConsenant(wordToTranslate);
这给出了几个错误。它说wordToTranslate。[0]没有足够的类型约束和startsWithVowel是错误的类型。完整的错误文本是
Severity Code Description Project File Line
Error The operator 'expr.[idx]' has been used on an object of indeterminate type based on information prior to this program point. Consider adding further type constraints Pig Latin FSharp
Severity Code Description Project File Line
Error This expression was expected to have type
bool
but here has type
('a * (char * char * char * char * char * char * char * char * char * char) list) list -> bool Pig Latin FSharp
我如何修复这种方法,以便它能按我的意愿行事?我对F#比较新,所以任何帮助都会非常感激!
答案 0 :(得分:3)
您需要在类型注释中使用括号,否则它将应用于返回值,而不是参数:
let translateWord (wordToTranslate : string) = ...
将参数传递给isInList
函数时,不需要括号和逗号。要分隔列表的元素,请使用;
而不是,
(,
用于分隔元组的元素。)
let startsWithVowel = isInList wordToTranslate.[0] ['A'; 'E'; 'I'; 'O'; 'U'; 'a'; 'e'; 'i'; 'o'; 'u']
这将解决编译错误。
顺便说一句,以下内容更清晰,更快,并且会给您相同的结果:
let startsWithVowel = Seq.contains wordToTranslate.[0] "AEIOUaeiou"