Skip to content

Instantly share code, notes, and snippets.

@LearningJournal
Last active October 8, 2019 14:29
Show Gist options
  • Save LearningJournal/e2cfc29f2453a14d3a393f15b307b505 to your computer and use it in GitHub Desktop.
Save LearningJournal/e2cfc29f2453a14d3a393f15b307b505 to your computer and use it in GitHub Desktop.
def doubler(i: Int) = { i * 2 }
(i: Int) => { i * 2 }
val d = (i: Int) => { i * 2 }
d(3)
//Output:- 6
def getOps(c: Int) = {
def doubler(x: Int) = x * 2
def tripler(x: Int) = x * 3
if (c > 0)
doubler _
else
tripler _
}
def getOps2(c: Int) = {
if (c > 0) (i: Int) => i * 2
else (i: Int) => i * 3
}
def getOps2(c: Int) = (i: Int) => {
if (c > 0) i * 2
else i * 3
}
val x = mydata.doThis(a).
.thenThis(b)
.andThenThis(c)
.doThisToo(d)
.andFinallyThis(e)
def getHike(salary:Double) = salary * p/100
def getHike(salary: Double) = salary * p / 100
/* Output:-
<console>:7: error: not found: value p
*/
var p = 10
def getHike(salary: Double) = salary * p / 100
getHike(5000)
//res0: Double = 500.0
def sumOfX(f: Int => Int, a: Int, b: Int): Int =
if (a > b) 0 else f(a) + sumOfX(f, a + 1, b)
def div(x: Double, y: Double): Double = x / y
//div: (x: Double, y: Double)Double
div(1, _: Double)
//res2: Double => Double = <function1>
val inverse = div(1, _: Int)
inverse(10)
//res3: Double = 0.1
sumOfX(x => x, 1, 5)
sumOfX(x => x * x, 1, 5)
sumOfX(x => x * x * x, 1, 5)
val sumOfCubes = sumOfX(x => x * x * x, _: Int, _: Int)
def applySums(f: (Int, Int) => Int) =
println("I am applying the sum of 1 to 5 and answer is = " + f(1, 5))
applySums(sumOfX(x => x * x * x, _: Int, _: Int))
applySums(sumOfX(x => x * x, _: Int, _: Int))
//Define a range
val r = 1 to 5
//r: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5)
//Option 1 - define a function value and then pass it
val f = (x: Int) => x + 10
//f: Int => Int = <function1>
r.map(f)
//res2: scala.collection.immutable.IndexedSeq[Int] = Vector(11, 12, 13, 14, 15)
//Option 2 - pass an inline function value as a single step
r.map(x => x + 10)
//res0: scala.collection.immutable.IndexedSeq[Int] = Vector(11, 12, 13, 14, 15)
r.map(x => x + 10)
r.reduce((x, y) => x * y)
r.map(x + 10)
r.reduce(x * y)
r.map(_ + 10)
r.reduce(_ * _)
//Can you write this example using a placeholder syntax?
r.filter(x => x > 5)
//Yes
r.filter(_ > 5)
//Can you do this one also?
r.reduce((x, y) => x + y / x min y)
//"No"
var p = 10
def getHike(salary: Double) = salary * p / 100
getHike(5000)
//res1: Double = 500.0
p = 20
getHike(5000)
//res2: Double = 1000.0
def echo(s: String*) = s foreach println
//You can use it like this.
echo("One", "Two", "Three")
//You can pass as many arguments as you want.
echo("One", "Two", "Three", "Four", "Five")
//Even no arguments is fine
echo()
def echo(s: String*, i: Int) = s foreach println
var p = 10
def getHike(salary: Double) = {
p = p * 2
salary * p / 100
}
println(p)
//10
getHike(5000)
//res8: Double = 1000.0
println(p)
//20
val l = (1001 to 1005).toList
l.map(getHike)
def getHike = {
//Load employee and their current salary
val e: Map[Int, Double] = Map(
1001 -> 35000.00,
1002 -> 43000.00,
1003 -> 28000.00,
1004 -> 54000.00,
1005 -> 17000.00
)
// Some logic to derive percentage for each employee
val p: Map[Int, Double] =
Map(1001 -> 10.00, 1002 -> 12.00, 1003 -> 7.50, 1004 -> 6.80, 1005 -> 20.00)
(empID: Int) => (empID, e(empID) * p(empID) / 100.00)
}
val f = getHike
f: Int => (Int, Double) = <function1>
//Get Hike for an employee
f(1001)
//res10: (Int, Double) = (1001,3500.0)
//Get Hike for a non existant employee
f(1006)
//java.util.NoSuchElementException: key not found: 1006
def doubler(i: Int) = i * 2
var d = doubler _
d(5)
//Output:- res0: Int = 10
val r = 1 to 10
//Output:- r: scala.collection.immutable.Range.Inclusive =
//Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
r.map(doubler)
//Output:- res4: scala.collection.immutable.IndexedSeq[Int] =
//Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
def getOps(c: Int) = {
def doubler(x: Int) = x * 2
def tripler(x: Int) = x * 3
if (c > 0)
doubler _
else
tripler _
}
val d = getOps(1)
d(5)
//Output:- res6: Int = 10
def doubler(i: Int) = i * 2
def tripler(i: Int) = i * 3
def applyF(f: Int => Int, x: Int) = f(x)
applyF(doubler, 5)
//Output:- res0: Int = 10
applyF(tripler, 5)
//Output:- res1: Int = 15
def getOps(c: Int) = {
def doubler(x: Int) = x * 2
def tripler(x: Int) = x * 3
if (c > 0)
doubler _
else
tripler _
}
val d = getOps(2)
d(2)
//Output:- res6: Int = 4
var customers = Array("Mike", "Zara","Abdul","Peter")
for (i <- 0 to customers.length - 1) {
println("Hi " + customers(i));
}
def remindPayment(x: String) = println("Payment reminder for " + x)
var i = 0;
for (i <- 0 to customers.length - 1) {
remindPayment(customers(i));
}
forEach(customers, remindPayment)
forEach(vendors, sendPayment)
def forEach(a: Array[String], f: String => Unit) = {
for (i <- 0 to a.length - 1)
f(a(i));
}
customers foreach remindPayment
var s = "Hello World!"
//After initializing it once, you can change it later.
s = "Hello Scala!"
val v = "You cannot change me."
v = "Let me try."
//Output:- <console>:8: error: reassignment to val
3 + 1 = 4
//Let me rewrite the above expression in a different notation.
sum(3, 1) //returns 4
def iFactorial(n: Int): Int = {
var i = n
var f = 1
while (i > 0) {
f = f * i
i = i - 1
}
return f
}
def rFactorial(n: Int): Int = {
if (n <= 0)
return 1
else
return n * rFactorial(n - 1)
}
def factorial(i: Int): Int = {
println(s"Starting Factorial for $i")
def tFactorial(n: Int, f: Int): Int = {
if (n <= 0) f
else tFactorial(n - 1, n * f)
}
return tFactorial(i, 1)
}
val s = factorial(15) / factorial(11)
/*Output:-
Starting Factorial for 15
Starting Factorial for 11
s: Int = 50
*/
println(s)
//50
//define a new function
def twice(i: Int) = {
println("We have not used i yet")
i + i
}
//call the function
twice(factorial(15) / factorial(11))
/*Output:-
Starting Factorial for 15
Starting Factorial for 11
We have not used i yet
res7: Int = 100
*/
//define a HO function
def twice(f: => Int) = {
println("We have not used f yet")
f + f
}
//call the function
twice(factorial(15) / factorial(11))
/* Output:-
We have not used f yet
Starting Factorial for 15
Starting Factorial for 11
Starting Factorial for 15
Starting Factorial for 11
res8: Int = 100
*/
//define a function
def twice(f: => Int) = {
val i = f
println("We have not used i yet")
i + i
}
//Call the function
twice(factorial(15) / factorial(11))
/*Output: -
Starting Factorial for 15
Starting Factorial for 11
We have not used i yet
res9: Int = 100
*/
lazy val l = factorial(15) / factorial(11)
//Output:- l: Int = <lazy>
//now use the value l
println(l)
/* Output:-
Starting Factorial for 15
Starting Factorial for 11
50
*/
//define the function
def twice(f: => Int) = {
lazy val i = f
println("We did not use i yet")
i + i
}
//call the function
twice(factorial(15) / factorial(11))
/* Output:-
We did not use i yet
Starting Factorial for 15
Starting Factorial for 11
res1: Int = 100
*/
import scala.io._
val s = Source
.fromFile("error_log")
.getLines()
.toList
.filter(_.contains("[error]"))
.take(2)
s foreach println
val s = Source
.fromFile("error_log")
.getLines()
.toStream
.filter(_.contains("[error]"))
.take(2)
s foreach println
Source.fromFile("error_log").getLines().toStream
/*
res2: scala.collection.immutable.Stream[String]
= Stream([Sun Mar 7 16:02:00 2004] [notice] Apache/1.3.29 (Unix) configured -- resuming normal operations, ?)
*/
Source.fromFile("error_log").getLines().toStream.filter(_.contains("[error]"))
/*
res3: scala.collection.immutable.Stream[String]
= Stream([Sun Mar 7 21:16:17 2004] [error] [client 24.70.56.49] File does not exist: /home/httpd/twiki/view/Main/WebHome, ?)
*/
Source
.fromFile("error_log")
.getLines()
.toStream
.filter(_.contains("[error]"))
.take(2)
/*
res4: scala.collection.immutable.Stream[String]
= Stream([Sun Mar 7 21:16:17 2004] [error] [client 24.70.56.49] File does not exist: /home/httpd/twiki/view/Main/WebHome, ?)
*/
s foreach println
/*
[Sun Mar 7 21:16:17 2004] [error] [client 24.70.56.49] File does not exist: /home/httpd/twiki/view/Main/WebHome
[Mon Mar 8 07:27:36 2004] [error] [client 61.9.4.61] File does not exist: /usr/local/apache/htdocs/_vti_bin/owssvr.dll
*/
def fibFrom(a: Int, b: Int): Stream[Int] = a #:: fibFrom(b, a + b)
//You can create a series by calling a function.
val f = fibFrom(1, 2)
//evaluate only as many as you want.
f.takeWhile(_ < 10) foreach println
def myTest(x: Any) = {
x match {
case i: Integer => "It's an Integer = " + i
case s: String => "It's an String = " + s
case d: Double => "It's a double = " + d
case _ => "Oops! Something Else"
}
}
class Message(p_id: String, p_msg: String) {
val id = p_id;
val msg = p_msg;
}
val messageList = List(
Message("tom@gmail.com", "Message text 1"),
Message("7742394590", "Message text 2"),
Message("8326192398", "Message text 3"),
Message("lisa@gmail.com", "Message text 4"),
Message("lisa@yahoo.com", "Message text 5"),
Message("harry@gmail.com", "Message text 6")
)
class Message(p_id: String, p_msg: String) {
val id = p_id;
val msg = p_msg;
}
object Message {
def apply(id: String, msg: String) = new Message(id, msg)
def unapply(m: Message): Option[(String, String)] = {
if (m == null) None else Some(m.id, m.msg)
}
}
object EmailAddress {
def apply(uname: String, dname: String) = uname + "@" + dname
def unapply(str: String): Option[(String, String)] = {
val parts = str split "@"
if (parts.length == 2) Some(parts(0), parts(1)) else None
}
}
def testMessagePattern(l: List[Message]): String = {
l match {
case Nil => "Not found"
case Message(EmailAddress(u1, d1), _) :: Message(EmailAddress(u2, d2), _)
:: _ if (u1 == u2) =>
u1 + " got two successive emails"
case h :: t => testMessagePattern(t)
}
}
val messageList = List(
Message("tom@gmail.com", "Message text 1"),
Message("7742394590", "Message text 2"),
Message("8326192398", "Message text 3"),
Message("lisa@gmail.com", "Message text 4"),
Message("lisa@yahoo.com", "Message text 5"),
Message("harry@gmail.com", "Message text 6")
)
println(testMessagePattern(messageList))
def multiplyByTwo(i : Int): Int = { i * 2 }
var g = 10
def testRT(i: Int): Int = {
g = i + g;
return g
}
val v1 = testRT(5)
//Output:- v1: Int = 15
val v2 = testRT(5)
//Output:- v2: Int = 20
println("Hello Scala")
// Output:- Hello Scala
//The above line of code is a statement.
var x = 2 * Math.sqrt(10) / 5
// Output:- x: Double = 1.2649110640673518
//The above line of code is an expression.
def myResult(m: Int) = {
var r = ""
if (m >= 50)
r = "passed";
else
r = "failed";
println(r)
}
myResult(65)
//Output:- passed
val x = println("Hello")
/* Output:-
Hello
x: Unit = ()
*/
def myResult(m: Int) = if (m >= 50) "passed" else "failed"
//You can print your result by calling this function.
println(myResult(65))
def factorial(n: Int): Int = {
if (n <= 0)
return 1
else
return n * factorial(n - 1)
}
def factorial(n: Int): Int = {
if (n <= 0)
throw new Exception("boom!")
else
return n * factorial(n - 1)
}
factorial(5)
/*Output:-
java.lang.Exception: boom!
at .factorial(<console>:10)
at .factorial(<console>:12)
at .factorial(<console>:12)
at .factorial(<console>:12)
at .factorial(<console>:12)
at .factorial(<console>:12)
at .<init>(<console>:9)
*/
def factorial(n: Int, f: Int): Int = {
if (n <= 0)
return f
else
return factorial(n - 1, n * f)
}
//So, f must be one for this function to work.
factorial(5, 1)
def factorial(n: Int, f: Int): Int = {
if (n <= 0)
throw new Exception("boom!")
else
return factorial(n - 1, n * f)
}
factorial(5, 1)
/* Output:-
java.lang.Exception: boom!
at .factorial(<console>:10)
at .<init>(<console>:9)
*/
def factorial(i: Int): Int = {
def tFactorial(n: Int, f: Int): Int = {
if (n <= 0) f
else tFactorial(n - 1, n * f)
}
return tFactorial(i, 1)
}
def functionName ([<parameterName> : <type> [, ....]]) : [return type] = {
function body
return [expr]
}
def myMax(x: Int, y: Int): Int = {
if (x > y)
return x;
else
return y;
}
['^(([^<>()[\]\\.,;:\\s@\"]+(\\.[^<>(),[\]\\.,;:\\s@\"]+)*)',
'|(\\".+\\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.',
'[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\\.)+',
'[a-zA-Z]{2,}))$'].join('')
def myMax(x: Int, y: Int): Int = {
if (x > y)
x
else
y
}
def myMax(x: Int, y: Int): Int = {
if (x > y) x else y
}
def myMax(x : Int, y : Int) : Int = if (x > y) x else y
def myMax(x : Int, y : Int) = if (x > y) x else y
def hWorld() = println("Hello World!")
hWorld()
hWorld
def hWorld = println("Hello World!")
//hWorld: Unit
hWorld
//Hello World!
hWorld()
//error: Unit does not take parameters
def doSomething(f: String => Unit, s: String) = f(s)
//We can use it like this.
doSomething(x => println("[" + x + "]"), "Hi There!")
//[Hi There!]
doSomething("Hi There!", x => println("[" + x + "]"))
//error: type mismatch;
doSomething(s = "Hi There!", f = x => println("[" + x + "]"))
def doSomething(f: String => Unit = println, s: String) = f(s)
doSomething(s = "Hi There!")
//Hi There!
def sumOfX(f: Int => Int, a: Int, b: Int): Int =
if (a > b) 0 else f(a) + sumOfX(f, a + 1, b)
def sumOfX(f: Int => Int)(a: Int, b: Int): Int =
if (a > b) 0 else f(a) + sumOfX(f)(a + 1, b)
sumOfX(x => x * x)(1, 5)
val si = sumOfX(x => x * x * x) _
//A Higher order function that returns another function
def sumOfY(f: Int => Int): (Int, Int) => Int =
(a: Int, b: Int) => if (a > b) 0 else f(a) + sumOfX(f)(a + 1, b)
//You can call it as below
sumOfY(x => x * x)(1, 5)
//This is exactly same as sumOfX shown in earlier example
sumOfX(x => x * x)(1, 5)
val s = "Hello World!"
val l = 5
//By default, it is an Integer, but I can specify the data type
val l: Long = 5
//Another alternative for enforcing the data type.
val l = 5: Long
([<parameterName> : <type> [, ....]]) => {
function body
return [expr]
} : [return type]
//Function literal example
val f = (x: Int) => { x + 5 }
//Compare it with String literal
val s = "Hello World!"
//You can enforce the return type
val f = (x: Int) => { x + 5 }: Int
val l: Long = 5
//Can we do the same with the function literal?
val f: Int => Int = (x: Int) => { x + 5 }
val myFun: (Int, String) => String =
(x: Int, s: String) => { s + x + s }: String
//Recomended syntax
val myFun = (x: Int, s: String) => s + x + s
val f = (x: Int) => x + 10
f(10)
//res0: Int = 20
val f = new Function1[Int, Int] {
def apply(x: Int): Int = x + 10
}
f(10)
//res1: Int = 20
int Decorator (5, (y: Int) => "[" + y + "]")
//res3: String = [5]
int Decorator (5, (y: Int) => "-" + y + "-")
//res4: String = -5-
int Decorator (5, (y: Int) => "Page " + y + "-")
//res5: String = Page 5-
sumOfX(3, 5, (x, y) => x + y)
//res7: Int = 8
sumOfX(3, 5, (x, y) => x * x + y * y)
//res8: Int = 34
sumOfX(3, 5, (x, y) => x * x * x + y * y * y)
//res9: Int = 152
def sumOfX(x: Int, y: Int, f: (Int, Int) => Int) = f(x, y)
def intDecorator(x: Int, f: Int => String) = f(x)
def sumOfX(f: (Int, Int) => Int) = {
def myLocalFunc(x: Int, y: Int) = f(x, y)
println("I am returning a function")
myLocalFunc _
}
//sumOfX: (f: (Int, Int) => Int)(Int, Int) => Int
//Step 1 - Provide the logic
val simpleSum = sumOfX((x, y) => x + y)
/* Output: -
I am returning a function
simpleSum: (Int, Int) => Int = <function2>
*/
//Step 2 - Canculate simple sums
simpleSum(3, 5)
//res10: Int = 8
-----------------------------
//Step 1 - Provide the logic
val sumOfSquare = sumOfX((x, y) => x * x + y * y)
/* Output: -
I am returning a function
sumOfSquare: (Int, Int) => Int = <function2>
*/
//Step 2 - Canculate sum of squares
sumOfSquare(3, 5)
//res11: Int = 34
def sumOfX(f: (Int, Int) => Int) = {
println("I am returning a function")
(x: Int, y: Int) => f(x, y)
}
def sumOfX(f: (Int, Int) => Int) = (x: Int, y: Int) => {
println("I am returning a function")
f(x, y)
}
import scala.io.Source
import scala.io.Source._
def getErrors(fileName: String) = {
def isError(line: String) = {
if (line.contains("[error]")) true else false
}
val f = Source.fromFile(fileName)
for (l <- f.getLines() if isError(l)) yield l
}
getErrors("error_log") foreach println
def div(x: Double, y: Double): Double = x / y
def add(x: Double, y: Double): Double = x + y
def inv(y: Double): Double = 1.0 / y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment