0
votes

I'm trying to create a function which can count vowels in a given String. Here is what I'm trying to do. I'm trying to solve the problem only with pipe operator and composition(>>) operator.

let vowels = ["a";"e";"i";"o";"u"]

let isVowel = fun c-> vowels |> List.contains c

let inline vowelCount string1 =
 string1
|> Seq.toList
|> List.filter isVowel

This is the problem I'm getting when i run the code in F# interactive:

"error FS0001: The type 'string' is not compatible with the type 'seq'"

Where am i doing wrong? What do i fail to understand? Thanks in advance.

3

3 Answers

3
votes

It seems what you want is to define vowels as a char list rather than a string list:

let vowels = ['a';'e';'i';'o';'u']

This single change would make your code compile, although not meet it's goal.

let vowels = ['a';'e';'i';'o';'u']

let isVowel = fun c-> vowels |> List.contains c

let inline vowelCount string1 =
 string1
|> Seq.toList
|> List.filter isVowel

vowelCount "qwerty"

Here is an alternative solution to meet your requirements of counting vowels in a string

let vowels = ['a';'e';'i';'o';'u']
let isVowel c = List.contains c vowels
let vowelCount = Seq.filter isVowel >> Seq.length
3
votes

You could also directly do it using the Seq.sumBy function :

let vowelcount : seq<char> -> int = 
    Seq.sumBy (function 'a'|'e'|'i'|'o'|'u' -> 1 | _ -> 0) 
1
votes

Where am i doing wrong? What do i fail to understand? Thanks in advance.

  1. You are posting code that compiles and saying there is a type error. Actually it is subsequent code that you did not include that gives the error.
  2. You are not examining the type signatures of your code. Intellisense will tell you the type signatures of your functions and will tell you that string1 is a seq<string>.
  3. You are overusing type inference. If you know what the type of a function input is then you can annotate it (for example string1:string instead of string1). This would then show an error earlier in the code (when you are trying to apply List.filter isVowel to a char list).