Home > Blockchain >  how use functional programming in scala function
how use functional programming in scala function

Time:01-21

I am developing translate function in Scala. It consists to insert the "av" character, just before a vowel-like 'a' , 'e' , 'i', 'o' or 'u'. Note that text string has length restrictions. It should not has a length of more than 225 characters and if it's empty, it should return an empty string: In another world: if

text = "abdcrfehilmoyr"

the result should be : "avabdcrfehavilmavoyr"

So, I developed this function :

def translate(text: String): String = {
  var voyelle = Array('a', 'e', 'i', 'o', 'u')
  for (w <- (0,text.length())){
    if ((text.contains(voyelle[w]) == true)) {
      text.patch(w, "av", 0)
    }
  }
}

Is there a way, to use instead functional programming like map, flat map functions to simplify the code ?

CodePudding user response:

String is effectively a collection of char's so you can treat it like one. For example:

val result = text
  .map(c => if (voyelle.contains(c)) "av"   c else c.toString)
  .mkString

CodePudding user response:

How about

   text.replaceAll("([aeiou])", "av$1")

CodePudding user response:

You can just use flatMap

def translate(text: String): String = {
  val vowels = Set('a', 'e', 'i', 'o', 'u')
  text.trim.toLowerCase.flatMap { c =>
    if (vowels.contains(c)) s"av${c}"
    else c.toString
  }
}

code running here.

  •  Tags:  
  • Related