SlideShare a Scribd company logo
Data Structures In Scala


           Meetu Maltiar
        Principal Consultant
              Knoldus
Agenda


Queue
Binary Tree
Binary Tree Traversals
Functional Queue

Functional Queue is a data structure that has three
operations:
 head: returns first element of the Queue
 tail: returns a Queue without its Head
 enqueue: returns a new Queue with given element at Head
 Has therefore First In First Out (FIFO) property
Functional Queue Continued
scala> val q = scala.collection.immutable.Queue(1, 2, 3)
q: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3)


scala> val q1 = q enqueue 4
q1: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3, 4)


scala> q
res3: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3)


scala> q1
res4: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3, 4)
Simple Queue Implementation
class SlowAppendQueue[T](elems: List[T]) {

    def head = elems.head

    def tail = new SlowAppendQueue(elems.tail)

    def enqueue(x: T) = new SlowAppendQueue(elems ::: List(x))

}




Head and tail operations are fast. Enqueue operation is slow as its performance is directly
proportional to number of elements.
Queue Optimizing Enqueue
class SlowHeadQueue[T](smele: List[T]) {
  // smele is elems reversed

    def head = smele.last // Not efficient

    def tail = new SlowHeadQueue(smele.init) // Not efficient

    def enqueue(x: T) = new SlowHeadQueue(x :: smele)
}




smele is elems reversed. Head operation is not efficient. Neither is tail operation. As both
last and init performance is directly proportional to number of elements in Queue
Functional Queue
class Queue[T](private val leading: List[T], private val trailing:
List[T]) {

    private def mirror =
      if (leading.isEmpty) new Queue(trailing.reverse, Nil)
      else this

    def head = mirror.leading.head

    def tail = {
      val q = mirror
      new Queue(q.leading.tail, q.trailing)
    }

    def enqueue(x: T) = new Queue(leading, x :: trailing)
}
Binary Search Tree

BST is organized tree.

BST has nodes one of them is specified as Root node.

Each node in BST has not more than two Children.

Each Child is also a Sub-BST.

Child is a leaf if it just has a root.
Binary Search Property

The keys in Binary Search Tree is stored to satisfy
following property:

Let x be a node in BST.
If y is a node in left subtree of x
Then Key[y] less than equal key[x]

If y is a node in right subtree of x
Then key[x] less than equal key[y]
Binary Search Property

        The Key of the root is 6

        The keys 2, 5 and 5 in left subtree is no
        larger than 6.

        The key 5 in root left child is no smaller
        than the key 2 in that node's left
        subtree and no larger than key 5 in the
        right sub tree
Tree Scala Representation
case class Tree[+T](value: T, left:
Option[Tree[T]], right: Option[Tree[T]])


This Tree representation is a recursive definition and has type
parameterization and is covariant due to is [+T] signature

This Tree class definition has following properties:
1. Tree has value of the given node
2. Tree has left sub-tree and it may have or do not contain value
3. Tree has right sub-tree and it may have or do not contain value

It is covariant to allow subtypes to be contained in the Tree
Tree In-order Traversal
BST property enables us to print out all
the Keys in a sorted order using simple
recursive In-order traversal.

It is called In-Order because it prints
key of the root of a sub-tree between
printing of the values in its left sub-
tree and printing those in its right sub-
tree
Tree In-order Algorithm
INORDER-TREE-WALK(x)
1. if x != Nil
2.   INORDER-TREE-WALK(x.left)
3.   println x.key
4.   INORDER-TREE-WALK(x.right)



For our BST in example before the output expected will be:
255678
Tree In-order Scala
  def inOrder[A](t: Option[Tree[A]], f: Tree[A] =>
Unit): Unit = t match {
    case None =>
    case Some(x) =>
      if (x.left != None) inOrder(x.left, f)
      f(x)
      if (x.right != None) inOrder(x.right, f)
  }
Tree Pre-order Algorithm
PREORDER-TREE-WALK(x)
1. if x != Nil
2.   println x.key
3.   PREORDER-TREE-WALK(x.left)
4.   PREORDER-TREE-WALK(x.right)



For our BST in example before the output expected will be:
652578
Tree Pre-order Scala
def preOrder[A](t: Option[Tree[A]], f: Tree[A]
=> Unit): Unit = t match {
    case None =>
    case Some(x) =>
      f(x)
      if (x.left != None) inOrder(x.left, f)
      if (x.right != None) inOrder(x.right, f)
  }




Pre-Order traversal is good for creating a copy of the Tree
Tree Post-Order Algorithm
POSTORDER-TREE-WALK(x)
1. if x != Nil
2.   POSTORDER-TREE-WALK(x.left)
3.   POSTORDER-TREE-WALK(x.right)
4.   println x.key


For our BST in example before the output expected will be:
255876

Useful in deleting a tree. In order to free up resources a
node in the tree can only be deleted if all the children (left
and right) are also deleted

Post-Order does exactly that. It processes left and right
sub-trees before processing current node
Tree Post-order Scala
def postOrder[A](t: Option[Tree[A]], f: Tree[A]
=> Unit): Unit = t match {
    case None =>
    case Some(x) =>
      if (x.left != None) postOrder(x.left, f)
      if (x.right != None) postOrder(x.right, f)
      f(x)
  }
References
1. Cormen Introduction to Algorithms

2. Binary Search Trees Wikipedia

3. Martin Odersky “Programming In Scala”

4. Daniel spiewak talk “Extreme Cleverness:
Functional Data Structures In Scala”
Thank You!!
Ad

More Related Content

What's hot (18)

Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
Tim (dev-tim) Zadorozhniy
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
Mohsen Zainalpour
 
Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collections
Knoldus Inc.
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
goncharenko
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Philip Schwarz
 
Frp2016 3
Frp2016 3Frp2016 3
Frp2016 3
Kirill Kozlov
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
Knoldus Inc.
 
JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework
Jyothishmathi Institute of Technology and Science Karimnagar
 
Practical cats
Practical catsPractical cats
Practical cats
Raymond Tay
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
Constantine Nosovsky
 
Scala Parallel Collections
Scala Parallel CollectionsScala Parallel Collections
Scala Parallel Collections
Aleksandar Prokopec
 
R reference card
R reference cardR reference card
R reference card
Hesher Shih
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02
Nguyen Tuan
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
Java 8 - An Introduction by Jason Swartz
Java 8 - An Introduction by Jason SwartzJava 8 - An Introduction by Jason Swartz
Java 8 - An Introduction by Jason Swartz
Jason Swartz
 
R교육1
R교육1R교육1
R교육1
Kangwook Lee
 
R short-refcard
R short-refcardR short-refcard
R short-refcard
conline
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collections
Knoldus Inc.
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
goncharenko
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Philip Schwarz
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
Knoldus Inc.
 
R reference card
R reference cardR reference card
R reference card
Hesher Shih
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02
Nguyen Tuan
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
Java 8 - An Introduction by Jason Swartz
Java 8 - An Introduction by Jason SwartzJava 8 - An Introduction by Jason Swartz
Java 8 - An Introduction by Jason Swartz
Jason Swartz
 
R short-refcard
R short-refcardR short-refcard
R short-refcard
conline
 

Similar to Data structures in scala (20)

Intro Python Data Structures.pptx Intro Python Data Structures.pptx
Intro Python Data Structures.pptx Intro Python Data Structures.pptxIntro Python Data Structures.pptx Intro Python Data Structures.pptx
Intro Python Data Structures.pptx Intro Python Data Structures.pptx
judyhilly13
 
CS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdfCS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdf
ssuser034ce1
 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scala
Raymond Tay
 
lecture 11
lecture 11lecture 11
lecture 11
sajinsc
 
Zippers
ZippersZippers
Zippers
David Overton
 
Soft Heaps
Soft HeapsSoft Heaps
Soft Heaps
⌨️ Andrey Goder
 
Address calculation-sort
Address calculation-sortAddress calculation-sort
Address calculation-sort
Vasim Pathan
 
Recursion Lecture in Java
Recursion Lecture in JavaRecursion Lecture in Java
Recursion Lecture in Java
Raffi Khatchadourian
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queue
Rai University
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queue
Rai University
 
Chapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptxChapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptx
atharvdeshpande20
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queue
Rai University
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structure
Shakil Ahmed
 
Data structures
Data structures Data structures
Data structures
Rokonuzzaman Rony
 
8 chapter4 trees_bst
8 chapter4 trees_bst8 chapter4 trees_bst
8 chapter4 trees_bst
SSE_AndyLi
 
8.binry search tree
8.binry search tree8.binry search tree
8.binry search tree
Chandan Singh
 
Recursion Lecture in C++
Recursion Lecture in C++Recursion Lecture in C++
Recursion Lecture in C++
Raffi Khatchadourian
 
CS-102 BST_27_3_14.pdf
CS-102 BST_27_3_14.pdfCS-102 BST_27_3_14.pdf
CS-102 BST_27_3_14.pdf
ssuser034ce1
 
R Programming Reference Card
R Programming Reference CardR Programming Reference Card
R Programming Reference Card
Maurice Dawson
 
Mementopython3 english
Mementopython3 englishMementopython3 english
Mementopython3 english
yassminkhaldi1
 
Intro Python Data Structures.pptx Intro Python Data Structures.pptx
Intro Python Data Structures.pptx Intro Python Data Structures.pptxIntro Python Data Structures.pptx Intro Python Data Structures.pptx
Intro Python Data Structures.pptx Intro Python Data Structures.pptx
judyhilly13
 
CS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdfCS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdf
ssuser034ce1
 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scala
Raymond Tay
 
lecture 11
lecture 11lecture 11
lecture 11
sajinsc
 
Address calculation-sort
Address calculation-sortAddress calculation-sort
Address calculation-sort
Vasim Pathan
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queue
Rai University
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queue
Rai University
 
Chapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptxChapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptx
atharvdeshpande20
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queue
Rai University
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structure
Shakil Ahmed
 
8 chapter4 trees_bst
8 chapter4 trees_bst8 chapter4 trees_bst
8 chapter4 trees_bst
SSE_AndyLi
 
CS-102 BST_27_3_14.pdf
CS-102 BST_27_3_14.pdfCS-102 BST_27_3_14.pdf
CS-102 BST_27_3_14.pdf
ssuser034ce1
 
R Programming Reference Card
R Programming Reference CardR Programming Reference Card
R Programming Reference Card
Maurice Dawson
 
Mementopython3 english
Mementopython3 englishMementopython3 english
Mementopython3 english
yassminkhaldi1
 
Ad

More from Meetu Maltiar (9)

Hands-On AWS: Java SDK + CLI for Cloud Developers
Hands-On AWS: Java SDK + CLI for Cloud DevelopersHands-On AWS: Java SDK + CLI for Cloud Developers
Hands-On AWS: Java SDK + CLI for Cloud Developers
Meetu Maltiar
 
Introducing Akka
Introducing AkkaIntroducing Akka
Introducing Akka
Meetu Maltiar
 
Fitnesse With Scala
Fitnesse With ScalaFitnesse With Scala
Fitnesse With Scala
Meetu Maltiar
 
Akka 2.0 Reloaded
Akka 2.0 ReloadedAkka 2.0 Reloaded
Akka 2.0 Reloaded
Meetu Maltiar
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
Meetu Maltiar
 
Scala test
Scala testScala test
Scala test
Meetu Maltiar
 
Scala Collections
Scala CollectionsScala Collections
Scala Collections
Meetu Maltiar
 
Easy ORMness with Objectify-Appengine
Easy ORMness with Objectify-AppengineEasy ORMness with Objectify-Appengine
Easy ORMness with Objectify-Appengine
Meetu Maltiar
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Hands-On AWS: Java SDK + CLI for Cloud Developers
Hands-On AWS: Java SDK + CLI for Cloud DevelopersHands-On AWS: Java SDK + CLI for Cloud Developers
Hands-On AWS: Java SDK + CLI for Cloud Developers
Meetu Maltiar
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
Meetu Maltiar
 
Easy ORMness with Objectify-Appengine
Easy ORMness with Objectify-AppengineEasy ORMness with Objectify-Appengine
Easy ORMness with Objectify-Appengine
Meetu Maltiar
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Ad

Recently uploaded (20)

Cybersecurity Tools and Technologies - Microsoft Certificate
Cybersecurity Tools and Technologies - Microsoft CertificateCybersecurity Tools and Technologies - Microsoft Certificate
Cybersecurity Tools and Technologies - Microsoft Certificate
VICTOR MAESTRE RAMIREZ
 
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
ICT Frame Magazine Pvt. Ltd.
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Alan Dix
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdfICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
Eryk Budi Pratama
 
How to Build an AI-Powered App: Tools, Techniques, and Trends
How to Build an AI-Powered App: Tools, Techniques, and TrendsHow to Build an AI-Powered App: Tools, Techniques, and Trends
How to Build an AI-Powered App: Tools, Techniques, and Trends
Nascenture
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptxUiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
anabulhac
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
Build With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdfBuild With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdf
Google Developer Group - Harare
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Top-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptxTop-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptx
BR Softech
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient CareAn Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
Cyntexa
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Cybersecurity Tools and Technologies - Microsoft Certificate
Cybersecurity Tools and Technologies - Microsoft CertificateCybersecurity Tools and Technologies - Microsoft Certificate
Cybersecurity Tools and Technologies - Microsoft Certificate
VICTOR MAESTRE RAMIREZ
 
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
ICT Frame Magazine Pvt. Ltd.
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Alan Dix
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdfICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
Eryk Budi Pratama
 
How to Build an AI-Powered App: Tools, Techniques, and Trends
How to Build an AI-Powered App: Tools, Techniques, and TrendsHow to Build an AI-Powered App: Tools, Techniques, and Trends
How to Build an AI-Powered App: Tools, Techniques, and Trends
Nascenture
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptxUiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
anabulhac
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Top-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptxTop-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptx
BR Softech
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient CareAn Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
Cyntexa
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 

Data structures in scala

  • 1. Data Structures In Scala Meetu Maltiar Principal Consultant Knoldus
  • 3. Functional Queue Functional Queue is a data structure that has three operations: head: returns first element of the Queue tail: returns a Queue without its Head enqueue: returns a new Queue with given element at Head Has therefore First In First Out (FIFO) property
  • 4. Functional Queue Continued scala> val q = scala.collection.immutable.Queue(1, 2, 3) q: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3) scala> val q1 = q enqueue 4 q1: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3, 4) scala> q res3: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3) scala> q1 res4: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3, 4)
  • 5. Simple Queue Implementation class SlowAppendQueue[T](elems: List[T]) { def head = elems.head def tail = new SlowAppendQueue(elems.tail) def enqueue(x: T) = new SlowAppendQueue(elems ::: List(x)) } Head and tail operations are fast. Enqueue operation is slow as its performance is directly proportional to number of elements.
  • 6. Queue Optimizing Enqueue class SlowHeadQueue[T](smele: List[T]) { // smele is elems reversed def head = smele.last // Not efficient def tail = new SlowHeadQueue(smele.init) // Not efficient def enqueue(x: T) = new SlowHeadQueue(x :: smele) } smele is elems reversed. Head operation is not efficient. Neither is tail operation. As both last and init performance is directly proportional to number of elements in Queue
  • 7. Functional Queue class Queue[T](private val leading: List[T], private val trailing: List[T]) { private def mirror = if (leading.isEmpty) new Queue(trailing.reverse, Nil) else this def head = mirror.leading.head def tail = { val q = mirror new Queue(q.leading.tail, q.trailing) } def enqueue(x: T) = new Queue(leading, x :: trailing) }
  • 8. Binary Search Tree BST is organized tree. BST has nodes one of them is specified as Root node. Each node in BST has not more than two Children. Each Child is also a Sub-BST. Child is a leaf if it just has a root.
  • 9. Binary Search Property The keys in Binary Search Tree is stored to satisfy following property: Let x be a node in BST. If y is a node in left subtree of x Then Key[y] less than equal key[x] If y is a node in right subtree of x Then key[x] less than equal key[y]
  • 10. Binary Search Property The Key of the root is 6 The keys 2, 5 and 5 in left subtree is no larger than 6. The key 5 in root left child is no smaller than the key 2 in that node's left subtree and no larger than key 5 in the right sub tree
  • 11. Tree Scala Representation case class Tree[+T](value: T, left: Option[Tree[T]], right: Option[Tree[T]]) This Tree representation is a recursive definition and has type parameterization and is covariant due to is [+T] signature This Tree class definition has following properties: 1. Tree has value of the given node 2. Tree has left sub-tree and it may have or do not contain value 3. Tree has right sub-tree and it may have or do not contain value It is covariant to allow subtypes to be contained in the Tree
  • 12. Tree In-order Traversal BST property enables us to print out all the Keys in a sorted order using simple recursive In-order traversal. It is called In-Order because it prints key of the root of a sub-tree between printing of the values in its left sub- tree and printing those in its right sub- tree
  • 13. Tree In-order Algorithm INORDER-TREE-WALK(x) 1. if x != Nil 2. INORDER-TREE-WALK(x.left) 3. println x.key 4. INORDER-TREE-WALK(x.right) For our BST in example before the output expected will be: 255678
  • 14. Tree In-order Scala def inOrder[A](t: Option[Tree[A]], f: Tree[A] => Unit): Unit = t match { case None => case Some(x) => if (x.left != None) inOrder(x.left, f) f(x) if (x.right != None) inOrder(x.right, f) }
  • 15. Tree Pre-order Algorithm PREORDER-TREE-WALK(x) 1. if x != Nil 2. println x.key 3. PREORDER-TREE-WALK(x.left) 4. PREORDER-TREE-WALK(x.right) For our BST in example before the output expected will be: 652578
  • 16. Tree Pre-order Scala def preOrder[A](t: Option[Tree[A]], f: Tree[A] => Unit): Unit = t match { case None => case Some(x) => f(x) if (x.left != None) inOrder(x.left, f) if (x.right != None) inOrder(x.right, f) } Pre-Order traversal is good for creating a copy of the Tree
  • 17. Tree Post-Order Algorithm POSTORDER-TREE-WALK(x) 1. if x != Nil 2. POSTORDER-TREE-WALK(x.left) 3. POSTORDER-TREE-WALK(x.right) 4. println x.key For our BST in example before the output expected will be: 255876 Useful in deleting a tree. In order to free up resources a node in the tree can only be deleted if all the children (left and right) are also deleted Post-Order does exactly that. It processes left and right sub-trees before processing current node
  • 18. Tree Post-order Scala def postOrder[A](t: Option[Tree[A]], f: Tree[A] => Unit): Unit = t match { case None => case Some(x) => if (x.left != None) postOrder(x.left, f) if (x.right != None) postOrder(x.right, f) f(x) }
  • 19. References 1. Cormen Introduction to Algorithms 2. Binary Search Trees Wikipedia 3. Martin Odersky “Programming In Scala” 4. Daniel spiewak talk “Extreme Cleverness: Functional Data Structures In Scala”
  翻译: