I am trying to do an exercise in which you have to define a recursive function that is capable of returning a string with all the vowels of a string using another function that indicates if a Char is a vowel or not:
object ej8 {
def esVocal(letra:Char):Boolean={
var vocal:Boolean=false
if(letra=='a' || letra=='e' || letra=='i' || letra=='o' || letra=='u')vocal=true
return vocal
}
def vocales(cadena:String): String={}
It is quite difficult for me to see if the vowel function can be done recursively since it needs yes or yes from the esVocal function since it is the one that checks the letters one by one but I cannot find a valid solution without filling the stack or do weird things, thanks in advance.
You can implement the following pseudocode that provides a recursive mechanism in which 3 factors are taken into account: a string or string that is the source or main string, the position at which you start to traverse the string or string, and finally the stack to which you will add elements.
If you just want to display or print the values then you should not use a stack and just print to the screen when it is a vowel, you would just pass the string parameters to get the vowels and the starting position in the function. All the best! :)
PS: I have no experience in Scala but I think with this you can solve your problem.
I think I have found a valid solution:
I do not advise you to access the string by index (
cadena.charAt
). It is not well seen in functional programming and, in many cases, there is a better alternative. For example, can be useds.head
instead ofs.charAt(0)
, ors.tail
instead ofs.substring(1)
,Likewise, in scala it is recommended not to use the
return
to exit a function, that is more typical of imperative programming .Basically what you need is to create a "filter" , something as simple as:
We can create it as a recursive function, passing a check function as an argument, something like this:
With what we would finally have:
The filter function can be applied to more objects. We can create a generic filter function that works for any type of sequence:
With this definition, our function
vocales
would look like this:By the way, the function
esVocal
could also be made simpler:I would recommend you to use tail recursion
with that you should not have problems with the memory stack