简体   繁体   中英

F# Use result of boolean function in if statement

I'm trying to write a pig latin translator in F#. To translate, I need to know if a word starts with a vowel or not. To do that, I'm trying to use this function which I wrote...

(*Tests if an element is in a list*)
let isInList elementToFind listToCheck = 
    List.fold(fun a b -> a || b = elementToFind) false listToCheck;

to test if the first character in a word is in a list of all vowels. Here is what my attempt looks like

(*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);

Which is giving several errors. It's saying wordToTranslate.[0] doesn't have enough type constrants and startsWithVowel is of the wrong type. The full error texts are

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

How can I fix this approach so that it does what I want it to do? I'm relatively new to F# so any help would be greatly appreciated!

You need parenthesis in the type annotation, otherwise it applies to the return value, not parameter:

let translateWord (wordToTranslate : string) = ...

You do not need parenthesis and commas when passing arguments to isInList function. To separate elements of a list use ; instead of , ( , is used to separate elements of a tuple).

let startsWithVowel = isInList wordToTranslate.[0] ['A'; 'E'; 'I'; 'O'; 'U'; 'a'; 'e'; 'i'; 'o'; 'u']

That will fix the compilation errors.

By the way, the following is cleaner, faster and will give you the same results:

let startsWithVowel = Seq.contains wordToTranslate.[0] "AEIOUaeiou"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM