scala – function call – recursion tail

What is recursion tail in scala?

‘Recursion’ is a function that calls itself. A function that calls itself, for example, a function ‘A’ calls function ‘B’, which calls the function ‘C’.  It is a technique used frequently in functional programming.

 

In order for a tail recursive, the call back to the function must be the last function to be performed.

scala – better language

 In what ways Scala is better than other programming language?

a)      The arrays uses regular generics, while in other language, generics are bolted on as an afterthought and are completely separate but have overlapping behaviours with arrays.

b)      Scala has immutable “val” as a first class language feature. The “val” of scala is similar to Java final variables.  Contents may mutate but top  reference is immutable.

c)       Scala lets ‘if blocks’, ‘for-yield loops’, and ‘code’ in braces to return a value. It is more preferable, and eliminates the need for a separate ternary operator.

d)      Singleton has singleton objects rather than C++/Java/ C# classic static.  It is a cleaner solution

e)       Persistent immutable collections are the default and built into the standard library.

f)       It has native tuples and a concise code

g)      It has no boiler plate code

scala – pattern variable – start with lower case – all others constants

Variable or constant? Constant patterns can have symbolic names. You saw this already when we used Nil as a pattern. Here is a related example, where a pattern match involves the constants E (2.71828…) and Pi (3.14159…):
scala> import math.{E, Pi} import math.{E, Pi} scala> E match { case Pi => “strange math? Pi = “+ Pi case _ => “OK” }

res11: java.lang.String = OK
As expected, E does not match Pi, so the “strange math” case is not used. How does the Scala compiler know that Pi is a constant imported from scala.math,andnotavariablethatstandsfortheselectorvalueitself? Scala uses a simple lexical rule for disambiguation: a simple name starting with a lowercase letter is taken to be a pattern variable; all other references are taken to be constants.

 

 

scala – variable pattern

Variablepatterns A variable pattern matches any object, just like a wildcard. Unlike a wildcard, Scala binds the variable to whatever the object is. You can then use this variable to act on the object further. For example, Listing 15.6 shows a pattern match that has a special case for zero, and a default case for all other values. The default case uses a variable pattern so that it has a name for the value, no matter what it is.

 

expr match { case 0 => “zero” case somethingElse => “not zero: “+ somethingElse }