In: Computer Science
2. (WordValue.scala) Write a Scala function, to compute the value of a word. The value of a word is defined as the sum of the values of the individual letters of the word with value of "a" being 1, "b" being 2 etc. Upper and lower case letters have the same value. You can assume that the word consists of just letters. Here is the signature of the function:
def wordValue(s: String): Int = ???
For example, wordValue("Attitude") = 100. No loops/iterations allowed. Use recursion. Submit just the code for the function and any helpers you develop. We will call your function with our test cases.
Here iam providing the answer.Hope this helps you.If you have any doubts comment me i will clarify you.Please upvote,If you like my work.Thank you :- )
Here is the Scala script:-
object MyClass {
def wordValue(x:String): Int={
var len=x.length(); // to find the length of the string
if(len==0){ // if it is empty string return 0
return 0;
}
else{ // else convert str into lower case
var str = x.toLowerCase();
var first=str.charAt(0);//finding the first position character
var result=first.toInt-96; //find the result
return result+wordValue(x.slice(1,len)); //function calling recursively with 1st index to last
}
};
def main(args: Array[String]) {
println(wordValue("Attitude"))
}
}
Output:-