Blog

Scala – High order functions

Higher Order Functions in Scala

 

In Scala,  are the functions that take other functions as parameters or return a function as a result. This is because functions are first-class values in Scala. so we can say High order functions are the function for both methods and functions that can take functions as parameters or that return a function.

 This powerful functional programming concept enables developers to write concise, expressive, and reusable code by treating functions as first-class citizens.

In Scala, functions are values that can be assign to variables, passe as arguments to other functions, or return from functions. This flexibility allows for the creation of higher order functions, which enhance code modularity and enable sophisticat abstractions.

Common examples of higher order functions in Scala include map, filter, reduce, and fold, which operate on collections and accept functions as arguments to perform transformations, filtering, and aggregations. By leveraging higher order functions, developers can abstract away common patterns and algorithms, making code more generic and reusable.

Use case 1

val salaries = Seq(20000, 70000, 40000)
val doubleSalary = (x: Int) => x * 2
val newSalaries = salaries.map(doubleSalary)

doubleSalary is a function which takes a single Int, x, and returns x * 2. In general, the tuple on the left of the arrow => is a parameter list and the value of the expression on the right is what gets return. On line 3, the function doubleSalary gets appli to each element in the list of salaries.

Use case 2

val salaries = Seq(20000, 70000, 40000)
val newSalaries = salaries.map(x => x * 2)

Use case 3:

// Scala program of higher order
// function
// Creating object
object prwatech {
// Main method
    def main(arg:Array[String])
    {
      // Displays output by assigning 
        // value and calling functions
        println(apply(format, 15))
      
    }
      
    // A higher order function
    def apply(x: Double => String, y: Double) = x(y)
  
    // Defining a function for
    // the format and using a
    // method toString()
    def format[R](z: R) = "{" + z.toString() + "}"
      
}

output:

{15.0}
0
0

Scala – First Class Functions

scala First class function 

 

In functional programming, functions are assign to variables, pass to other functions as parameters, and return as values from other functions. Such functions are as First Class Functions.

In Scala, functions are consider first-class citizens, which means they can be treat just like any other value, such as integers or strings. This powerful feature enables functional programming paradigms where functions can be pass as arguments to other functions, return from functions as results, and assign to variables.

Scala’s support for first-class functions allows for concise and expressive code, promoting modular and reusable patterns. Functions can be defined using function literals ((parameters) => expression) or as named functions using the def keyword.

First-class functions enable higher-order functions, which are functions that take other functions as parameters or return functions as results. This higher-order function capability facilitates common functional programming patterns such as map, filter, reduce, and more.

Scala’s support for first-class functions is integral to its functional programming capabilities, enabling developers to write elegant and composable code. By leveraging first-class functions, developers can design more flexible and maintainable systems that embrace functional programming principles. This feature is particularly useful for asynchronous programming, event handling, and concurrency patterns in Scala applications. scala First class function

Use case 1:

Assign function as Variable
scala>(i:Int) => {i*2}
scala>val doubler = (i:Int) => {i*2}
scala>doubler(5)

2Use case 2:

Pass function as Parameter
scala>def operation(functionparam:(Int, Int) => Int){
       println(functionparam(10,5))
      }
scala> val sum = (x:Int, y:Int)=> x+y
scala>operation(sum);
scala>val diff = (x:Int, y:Int)=> x-y
scala>operation(diff);

Use case 3:

Return a Function
object prwatech {
   def main(args: Array[String]) {

    val doubleValue = doubler();
    print("Double of 2 = " + doubleValue(2));
  }

  def doubler() = (num: Int) => num * 2;
}
Output
Double of 2 = 4
0
0

Use case of Interface in GoLang

Best Practices for Interfaces in Go

 

In Go, interfaces play a crucial role in defining behavior and promoting flexibility in code design. Interfaces enable polymorphism by allowing different types to satisfy the same interface contract, facilitating code reuse and decoupling implementations from specific types.

To adhere to best practices when using interfaces in Go:

  1. Keep Interfaces Small and Focused: Define interfaces with a small number of methods that capture a specific behavior or capability. This promotes clarity and makes interfaces easier to implement.

  2. Use Interfaces Sparingly: Favor concrete types over interfaces unless there is a clear benefit to using an interface. Overusing interfaces can lead to unnecessary abstraction and increased complexity.

  3. Name Interfaces Descriptively: Use meaningful and descriptive names for interfaces that reflect their purpose and functionality. This enhances code readability and comprehension.

Interface is a protocol – a contract. It only describes the expect behavior, It is an abstract type.

Use Case 1:

Program to print value through interface.

package main

import “fmt”

funcmyfunc(a interface{}) {

            v := a.(string)

            fmt.Println(“value :”, v)

}

funcmain() {

            var v interface {

            } = “Prwatech”

            myfunc(v)

}

Output :

Use Case 2:

Program for geometric shapes.

package main

import (

    “fmt”

    “math”

)

type geometry interface {

area() float64

perim() float64

}

type rect struct {

    width, height float64

}

type circle struct {

    radius float64

}

func (r rect) area() float64 {

    return r.width * r.height

}

func (r rect) perim() float64 {

    return 2*r.width + 2*r.height

}

func (c circle) area() float64 {

    return math.Pi * c.radius * c.radius

}

func (c circle) perim() float64 {

    return 2 * math.Pi * c.radius

}

funcmeasure(g geometry) {

fmt.Println(g)

fmt.Println(g.area())

fmt.Println(g.perim())

}

funcmain() {

r := rect{width: 3, height: 4}

c := circle{radius: 5}

    measure(r)

    measure(c)

}

Output:

Use Case 3:

package main

import (

    “fmt”

)

funcmyFunc(a interface{}) {

fmt.Println(a)

}

funcmain() {

    var my_age int

my_age = 25

myFunc(my_age)

}

Output :

0
0

Use cases of recursion in GoLang

Use cases of recursion in GoLang

 

Recursion is a programming technique where a function calls itself directly or indirectly to solve a problem by breaking it down into smaller, similar subproblems. In GoLang (Go), recursion is supported and can be employed for various use cases across software development.

One common use case of recursion in Go is in algorithms involving tree structures or hierarchical data. Recursive functions can efficiently traverse and manipulate tree-like data structures such as binary trees, linked lists, or directory structures.

Another use case is in implementing algorithms like factorial computation or Fibonacci sequence generation, where each step relies on the solution of a smaller subproblem. Recursion can elegantly express these algorithms by reducing complex problems into simpler repetitive tasks.

Recursion is a concept to calling a function within a function itself.

Use Case 1:

Finite Recursion :  In finite function , the function stops at a finite number of steps.

Program – To print fibonacci series

package main

import “fmt”

func fib(i int) int {

            if i == 0 {

                        return 0

            }

            if i == 1 {

                        return 1

            }

            return fib(i-1) + fib(i-2)

}

func main() {

            var i int

            for i = 0; i< 10; i++ {

                        fmt.Printf(” %d  “, fib(i))

            }

}

Output :

Use Case 2:

Program to print numbers by recursive function.

package main

import (

            “fmt”

)

funcprintnum(n int) {

            if n > 0 {

                        printnum(n – 1)

                        fmt.Println(n)

            }

}

func main() {

            printnum(5)

}

Output :

Use Case 3:

Infinte Recursion : In infinite recursion the function doesn’t stop calling itself, it runs infinite times.

package main

import (

    “fmt”

)

func rec(){

fmt.Println(“Endless”)

    rec()

}

func main() { 

}

Output :

0
0

Use cases of functions in Golang

Use cases of functions in Golang

Functions in Go (Golang) are essential building blocks of software development, offering encapsulation, reusability, and modularity in code. They are used to define reusable blocks of logic that can be invoked multiple times with different inputs, enhancing code organization and readability.

One key use case of functions in Go is abstraction. By encapsulating specific tasks or behaviors into functions, developers can hide implementation details and expose only the necessary interfaces, promoting modular and maintainable code.

Functions also facilitate code reuse by allowing developers to define common operations as functions that can be invoked from multiple parts of the codebase. This promotes the “Don’t Repeat Yourself” (DRY) principle and reduces redundancy.

Function is a group of statements which is used to break large tasks into smaller tasks.

The Go standard libraries provides numerous built-in functions.

Defining a Functions

>> Func func_name ([Parameter_list]) [Return_type]

                         {

                                \\ body of a program

                          }

Use Case 1: Program to find maximum no.

package main

import “fmt”

func main() {

            var a int = 100

            1var b int = 211

            var c int

            c = max(a, b)

            fmt.Println(“Max value is:”, c)

}

func max(a, b int) int {

            if a > b {

                        return a

} else {

return b

            }

}

Output :

Use Case 2: Program to swap string

package main

import “fmt”

func swap(x, y string) (string, string) {

            return y, x

}

func main() {

            a, b := swap(“Prwatech”, “Bangalore”)

            fmt.Println(a, b)

}

Output :

Use Case 3:

package main 

import “fmt” 

type Employee struct { 

fname string 

lname string 

func (emp Employee) fullname(){ 

fmt.Println(emp.fname+” “+emp.lname) 

func main() { 

   e1 := Employee{ “Alex”,”A”} 

   e1.fullname() 

Output:

 

0
0

Go – if-else use cases

Go – if-else use cases

 

The if statement in Go is use to test the condition. If it evaluates to true, the body of the statement is executed. If it evaluates to false, if block is skip.

Syntax :

if(boolean_expression)

 {  

   /* statement(s) got executed only if the expression results in true */  

}  

Use Case 1:

package main 

import “fmt” 

funcmain() { 

     var a int = 10 

if( a % 2==0 ) {      // if condition is true then print the following

fmt.Printf(“a is even number” ) 

   } 

Output:

Use Case 2:

package main 

import “fmt” 

funcmain() { 

   var iint = 10; 

      if ( i%2 == 0 ) { 

      /* if condition is true then print the following */ 

fmt.Printf(“i is even number”); 

   } else { 

      /* if condition is false then print the following */ 

fmt.Printf(“i is odd number”); 

   } 

Output:

Use Case 3:

package main 

import “fmt” 

funcmain() { 

fmt.Print(“Enter number: “) 

   var i int 

fmt.Scanln(&i) 

fmt.Print(i) 

   /* check the boolean condition */ 

if( i % 2==0 ) { 

fmt.Println(” is even” ); 

   } else { 

fmt.Println(” is odd” ); 

   } 

Output:

Use Case 4:

package main 

import “fmt” 

funcmain() { 

fmt.Print(“Enter text: “) 

   var input int 

fmt.Scanln(&input) 

   if (input < 0 || input > 100) { 

fmt.Print(“Please enter valid no”) 

   } else if (input >= 0 && input <50  ) { 

fmt.Print(” Fail”) 

   } else if (input >= 50 && input < 60) { 

fmt.Print(” D Grade”) 

   } else if (input >= 60 && input <70  ) { 

fmt.Print(” C Grade”) 

   } else if (input >= 70 && input < 80) { 

fmt.Print(” B Grade”) 

   } else if (input >= 80 && input <90  ) { 

fmt.Print(” A Grade”) 

   } else if (input >= 90 && input <= 100) { 

fmt.Print(” A+ Grade”) 

   } 

Output:

 

0
0

Golang – Switch use cases

Golang Switch Case Conditional Statements

 

In Go (Golang), the switch statement provides a flexible and concise way to implement conditional branching based on the value of an expression. Unlike traditional switch statements in other languages, Go’s switch statement does not require explicit break statements; instead, it automatically breaks at the end of each case block unless followed by a fallthrough keyword.

The switch statement in Go can be used to evaluate various types of expressions, including integers, strings, and other comparable types. It supports multiple comma-separated values in each case, allowing for concise matching against multiple conditions.

Go’s switch statement also supports optional initialization statements that are scoped to the switch block, enabling the use of short-lived variables specific to each case. Additionally, the switch statement can be used without an expression, effectively creating an alternative to if-else chains based on boolean conditions.

Golang switch statements are similar to jump statements in algorithms.

Use Case 1:

package main 

import “fmt” 

func main() { 

fmt.Print(“Enter Number: “) 

  var i int 

fmt.Scanln(&i) 

   switch (i) { 

  case 1: 

fmt.Print(“the value is 10”) 

    case 2: 

fmt.Print(“the value is 20”) 

    case 3: 

fmt.Print(“the value is 30”) 

    case 4: 

fmt.Print(“the value is 40”) 

    default: 

fmt.Print(” It is not in bound “) 

   } 

Output:

Use Case 2:

package main

import “fmt”

func main() {

    switch day:=4; day{

       case 1:

fmt.Println(“Monday”)

       case 2:

fmt.Println(“Tuesday”)

       case 3:

fmt.Println(“Wednesday”)

       case 4:

fmt.Println(“Thursday”)

       case 5:

fmt.Println(“Friday”)

       case 6:

fmt.Println(“Saturday”)

       case 7:

fmt.Println(“Sunday”)

       default:

fmt.Println(“Invalid”)

   }

}

Output:

Use Case 3:

package main

import “fmt”

func main() {

    var value string = “five”

   switch value {

       case “one”:

fmt.Println(“C#”)

       case “two”, “three”:

fmt.Println(“Go”)

       case “four”, “five”, “six”:

fmt.Println(“Java”)

   } 

}

Output:

0
0

GoLang– Break use cases

Switch Case with Break in For Loop in Golang

 

In Go (or Golang), the switch statement provides a flexible and concise way to evaluate multiple conditions and execute different blocks of code based on the value of an expression. When combined with a for loop, the switch statement allows for dynamic decision-making within iterative processes.

In Go, unlike some other languages, the switch statement automatically breaks after executing a case block, meaning that there’s no need for an explicit break statement at the end of each case block. This behavior prevents fall-through, where execution would continue to the next case block without a break statement.

When using a switch statement inside a for loop in Go, each iteration of the loop evaluates the expression provided to the switch statement. Based on the evaluated value, the corresponding case block is executed, and control returns to the loop for the next iteration.

Break is used to exit from the loop.

Use Case 1:

package main  

import “fmt”  

func main() {  

   var  a int = 1  

   for a < 10{  

      fmt.Print(“Value of a is “,a,”\n”)  

      a++;  

      if a > 5{  

         /* terminate the loop using break statement */  

         break;  

    

Output:

Use Case 2:

package main  

import “fmt”  

func main() {  

   var a int  

   var b int  

   for a = 1; a <= 3; a++ {  

      for b = 1; b <= 3; b++ {  

fmt.Println(“Prwatech”)

         if (a == 2 && b == 2) {  

            break;  

 

         fmt.Print(a, ” “, b, “\n”)  

     

Output:

Use Case 3:

package main  

import “fmt”  

func main() {  

   var a int  

   var b int  

   for a = 1; a <= 3; a++ {  

      for b = 1; b <= 3; b++ { 

        if (a % 2 == 0) {  

            break;  

 

         fmt.Print(a, ” “, b, “\n”)  

 

Output:

0
0

Golang – For Loop use cases

 

 

In Go (or Golang), for loops are a fundamental construct used for iterating over collections, processing data, and executing repetitive tasks. The syntax of a for loop in Go is concise and versatile, offering different styles of iteration based on specific requirements.

A basic for loop in Go consists of an initialization statement, a condition expression, and an optional post statement. This structure allows developers to initialize loop variables, specify loop termination conditions, and define actions to be performed after each iteration.

Go supports traditional C-style for loops, where the initialization statement is used to declare loop variables, the condition expression determines when the loop should terminate, and the post statement is executed after each iteration. Additionally, Go offers a range-based for loop using the range keyword, which simplifies iteration over arrays, slices, maps, and channels.

For loop is use for repeating a set of statements number of times.

Use Case 1:

package main  

import “fmt”  

func main() {  

   for a := 0; a < 11; a++ {  

      fmt.Println(a)  

   }  

}  

Output:

Use Case 2:

package main  

import “fmt”  

func main() {  

   for a := 1; a < 3; a++ {  

      for b := 2;b > 0; b– {  

         fmt.Print(a,” “,b,”\n”)  

 

Output:

Use Case 3:

package main  

import “fmt”  

func main() {  

   s := 1  

   for s < 100 {  

      s += s  

      fmt.Println(s)  

 

Output:

0
0

Scala – Access Modifiers

The basics of Scala access modifiers

 

Access Modifiers in scala are utilized to characterize the access field of members of packages, classes or objects in scala. For utilizing an access modifier, you should remember its keyword for the definition of package, class or object. These modifiers will restrict access to the members to the specific part of code.

Scala access modifiers control the visibility and accessibility of classes, traits, methods, and fields within a Scala program. There are three primary access modifiers in Scala:

  1. Private: Members marked as private are accessible only within the enclosing scope, such as a class or object. Private members cannot be accessed from outside the enclosing scope, even by subclasses.

  2. Protected: Members marked as protected are accessible within the defining class and its subclasses. Protected members can be accessed by subclasses but not by other classes in the same package.

  3. Public (No Modifier): Members without explicit access modifiers are public by default. Public members are accessible from anywhere within the same package or from external packages.

Additionally, Scala supports package-level access modifiers (private[package] and protected[package]) that restrict visibility to specific packages.

Types of Access Modifiers

Private members

Protected members

Public members

Use case 1:

Private Members in Scala

class Prwatech {
private var a:Int=7
def show(){
a=6
println(a)
}
}
object access extends App{
var e=new Prwatech()
e.show()

}

output:

6

Use case 2:

Protected members in scala

class prwatech {
protected var a:Int=7
def show(){
a=8
println(a)
}
}
class prwatech1 extends prwatech{
def show1(){
a=9
println(a)
}
}
object access extends App{
var e=new prwatech()
e.show()
var e1=new prwatech1()
e1.show1()
//e.a=10
//println(e.a)
}

output:

8

9

Use case 3:

Public members in scala

class Example {
var a:Int=10
}
object access extends App{
var e=new Example()
e.a=5
println(e.a)
}

output:

5

0
0

Quick Support

image image