SlideShare a Scribd company logo
Comparing Haskell & Scala
Martin Ockajak from Zürich
Software Engineer
@martin_ockajak
Outline
●
Similarities
●
Conceptual differences
●
Haskell – extra features
●
Scala – extra features
●
Practical considerations
Similarities
Overview
●
High-level functional language
●
Product of programming language research
●
Haskell: Purely functional with strong side-effect handling
●
Scala: Functional and object-oriented
●
Automatic memory management
●
Static type checking
●
Type inference
• Haskell: global, variant of Hindley-Milner
• Scala: local, arguments require type annotations
Expressions
●
Everything is an expression producing a value
●
No operators, only infix functions with symbolic names
●
Haskell
let list = [1 + 2, 3]
in list !! 0
(#%) :: String -> String
(#%) x = x ++ "!"
●
Scala
val list = List(1 + 2, 3)
list(0)
def #%(x: String): String = x + "!"
Higher order functions
Functions as arguments and values
●
Haskell
applyAndInc f x = f x + 1
double x = x * 2
applyAndInc double 3
●
Scala
def applyAndInc(f: Int => Int, x: Int) = f(x) + 1
def double(x: Int): Int = x * 2
applyAndInc(double, 3)
Anonymous functions
Lambda expressions
●
Haskell
map (x -> x + 1) [1, 2, 3]
map (+ 1) [1, 2, 3]
●
Scala
List(1, 2, 3) map(x => x + 1)
List(1, 2, 3) map(_ + 1)List(1, 2, 3) map(x => x + 1)
List(1, 2, 3) map(_ + 1)
// partial function
List(1, 2, "3") collect { case x: Int => x + 1 }
Currying
Partial function application
●
Haskell
curried x y = x + y + 1
let partial = curried 1
in partial 2
uncurried = uncurry curried
curriedAgain = curry uncurried
●
Scala
def curried(x: Int)(y: Int): Int = x + y + 1
val partial = curried(1) _
partial(2)
val uncurried = Function.uncurried(curried _)
val curriedAgain = uncurried.curried
Encapsulation
Modules and access modifiers
●
Haskell
module Module (foo) where
foo x = bar x + 1
bar x = x * 2
●
Scala
object Encapsulation {
def foo(x: Int) = bar(x) + 1
private def bar(x: Int) = x * 2
}
Pattern matching with guards
●
Haskell
factorial 0 = 1
factorial n = n * factorial (n - 1)
pattern :: [Int] -> Int
pattern l | [x] <- l, x /= 0 = 1
| length l > 1 = 2
| otherwise = 0
●
Scala
def factorial(n: Int): Int = n match {
case 0 => 1
case n => n * factorial(n - 1)
}
def pattern(l: List[Int]): Int = l match {
case List(x) if x != 0 => 1
case l if l.size > 1 => 1
case _ => 0
}
List comprehensions
●
Haskell
[ (x, y) | x <- [1, 2, 3], y <- [4, 5, 6], x * y > 7 ]
[0 | _ <- [1..10] ]
●
Scala
for {
x <- List(1, 2, 3)
y <- List(4, 5, 6) if x * y > 7
} yield (x, y)
for (_ <- List(1 to 10)) yield 0
Monadic composition notation
●
Haskell
do
x <- [1, 2, 3]
y <- [4, 5, 6]
let z = (x + y)
return z
●
Scala
for {
x <- List(1, 2, 3)
y <- List(4, 5, 6)
z = x + y
} yield z
Type system
●
Parametric polymorphism
●
Ad hoc polymorphism
●
Haskell: Typeclasses
●
Scala: Typeclasses, method overloading, subtyping
●
Generalized algebraic data types
●
Multi-parameter type classes
●
Functional dependencies
Type system
●
Compound types
●
Type aliases
●
Existential types
●
Higher order types
●
Kinds
Algebraic data types
●
Haskell
data Tree a = Empty | Node a (Tree a) (Tree a)
●
Scala
sealed trait Tree[A]
case class Empty[A]() extends Tree[A]
case class Node[A](value: A, left: Tree[A], right: Tree[A]) extends
Tree[A]
Typeclasess
●
Haskell
class Equals a where
eq :: a -> a -> Bool
instance Equals Integer where
eq x y = x == y
tcEquals :: (Equals a) => a -> a -> Bool
tcEquals a b = eq a b
●
Scala
trait Equals[T] {
def eq(x: T, y: T): Boolean
}
implicit object EqualsInt extends Equals[Int] {
override def eq(x: Int, y: Int): Boolean = x == y
}
def tcEquals[T: Equals](x: T, y: T): Boolean =
implicitly[Equals[T]].eq(x, y)
Additional features
●
Implicit parameters
●
Annotations
●
Compile-time metaprogramming
●
Haskell: Template Haskell
●
Scala: Macros
Conceptual Differences
Purity
●
Haskell
●
Referential transparency
●
Side effects modeled via monads
●
Functions are pure
●
Scala
●
No referential transparency guarantees
●
Side effects allowed anywhere
●
Functions cannot be considered pure
Default evaluation strategy
●
Haskell
●
Non-strict lazy evaluation
●
Optional eager evaluation
●
Bang patterns
●
Strict modules
●
Scala
●
Strict eager evaluation
●
Optional lazy evaluation
●
Call-by-name parameter with lazy val pattern
Control flow
●
Haskell
●
Completely declarative
●
Exception handling via monads
●
No way to jump off current scope
●
Scala
●
Imperative constructs are supported
●
Exception handling at language level
●
Early return from a method
Haskell – extra features
Pointfree style
●
Omitting arguments in function definition
-- Point-wise
incp x = x + 1
expp x = 1 + 2 * x
-- Pointfree
incf = (+ 1)
expf = (1 +) . (2 *)
Polymorphic string literals
●
String syntax for various string-like types
string1 :: String
string1 = "string"
string2 :: Text
string2 = "text"
"test" :: IsString a => a
class IsString a where
fromString :: String -> a
Extended list comprehensions
●
Parallel (zip)
[ (x, y) | x <- [1, 2, 3] | y <- [4, 5, 6]]
●
Transform
cities = [ ("Berlin", 4.1), ("Milan", 5.2), ("Zurich", 1.3) ]
[ name ++ "!" | (name, size) <- cities,
then sortWith by size,
then drop 1 ]
●
Monad
[ x + y | x <- Just 1, y <- Just 2 ]
Deriving typeclass instances
●
Typeclasses: Eq, Ord, Enum, Bounded, Show, Read
data Coordinate = Planar Float Float | Spatial Float Float Float
deriving (Eq, Ord, Show)
Planar 1 2 == Planar 1 2
Spatial 1 2 1 < Spatial 1 2 3
show (Planar 1 2)
Higher rank polymorphism
●
Polymorphic function argument specified by the callee
id :: a -> a
id x = x
rank1 :: forall a. a -> a
rank1 x = x
rank2 :: (forall a. Num a => a -> a) -> (Int, Float)
rank2 f = (f 1, f 1.0)
rank2 (* 2)
Compiler extensions
●
View patterns & pattern synonyms
●
Type families
●
Data type generic programming
●
Kind polymorphism
●
And many more …
Scala – extra features
Imperative programming
●
Mutable state
●
Code blocks
●
While loops
var mutable = 1
mutable = 2
while (mutable < 3) {
List(1, 2, 3).foreach(_ => println("Missile fired"))
mutable += 1
}
throw new IllegalStateException("Abandon ship")
Object-oriented programming
●
Subtyping
●
Type variance, type bounds
●
Class-based inheritance system
●
Classes, traits, objects, abstract type members
●
Mixin class composition
●
Multiple inheritance with traits, self-typed references
Named and default arguments
●
Just like in Python
def very(standard: String, default: String = "value"): Unit = ()
very("text")
def handy(default: String = "value", standard: String): Unit = ()
handy(standard = "text")
String interpolation
●
Programmable via custom interpolators
val neat = 7
// standard library
val substitution = s"Is $neat"
val printf = f"Number is $neat%02d"
val noEscaping = raw"somenthing"
// external library
val document = json"""{ "hello": "world" }"""
Flexible scoping
●
Fields in traits
●
Abstract members
●
Nested function definitions
●
Multiple classes & objects in one source file
trait FlexibleScoping {
def abstractMethod(text: String): String
val abstractField: Int
def get: String = {
def compute: String = "result"
abstractMethod(compute)
}
}
Implicit conversion
●
Automated conversion of method arguments
●
Searches in current and various outer scopes
●
Method argument is converted using the implicit method
def more(value: Int): Int = 2 * value
implicit def convert(value: Vector[_]): Int = value.size
more(Vector(1, 2, 3))
// equivalent call with explicit conversion
more(convert(Vector(1, 2, 3)))
Structural typing
●
Type checking based on type contents not its name
●
Resolved at compile-time as opposed to duck-typing
def oneMore(countable: { def size: Int }): Unit = {
countable.size + 1
}
oneMore(List(1, 2, 3))
Dynamic typing
●
Programmable late binding at run-time
import scala.language.dynamics
object Accepts extends Dynamic {
def selectDynamic(name: String): Int = name.size
def applyDynamic(name: String)(args: Any*): String = name
}
Accepts.something
Accepts.hello("World")
Type system features
●
Type lambdas
●
F-bounded types
●
Self-recursive types
●
Path-dependent types
●
Instance bound types
●
Value classes
●
Type specialization
Practical considerations
Practicality - Haskell
●
Great productivity
●
High runtime performance
●
Clever community
●
Solid library and tooling ecosystem
●
Reasoning about can be tricky
●
Steep learning curve (real or imagined)
Practicality - Scala
●
Great productivity
●
High runtime performance
●
Clever community
●
Largest library and tooling ecosystem
●
Easy to transition from Java, C++, C#
●
Java interoperability somewhat pollutes the language
Thank you :-)
Ad

More Related Content

What's hot (20)

The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
Mohammed Irfan Shaikh
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in Scala
Ayush Mishra
 
An introduction to functional programming with Swift
An introduction to functional programming with SwiftAn introduction to functional programming with Swift
An introduction to functional programming with Swift
Fatih Nayebi, Ph.D.
 
Scala functions
Scala functionsScala functions
Scala functions
Knoldus Inc.
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
Templates
TemplatesTemplates
Templates
Nilesh Dalvi
 
An Introduction to Part of C++ STL
An Introduction to Part of C++ STLAn Introduction to Part of C++ STL
An Introduction to Part of C++ STL
乐群 陈
 
Java Tutorial Lab 8
Java Tutorial Lab 8Java Tutorial Lab 8
Java Tutorial Lab 8
Berk Soysal
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
•sreejith •sree
 
ScalaTrainings
ScalaTrainingsScalaTrainings
ScalaTrainings
Chinedu Ekwunife
 
Functional object
Functional objectFunctional object
Functional object
ruchijindal87
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
Knoldus Inc.
 
Teach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with ScalaTeach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with Scala
Damian Jureczko
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
Dhananjay Kumar
 
Scala
ScalaScala
Scala
Marcelo Cure
 
Linq Introduction
Linq IntroductionLinq Introduction
Linq Introduction
Neeraj Kaushik
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
Shalabh Chaudhary
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in Scala
Ayush Mishra
 
An introduction to functional programming with Swift
An introduction to functional programming with SwiftAn introduction to functional programming with Swift
An introduction to functional programming with Swift
Fatih Nayebi, Ph.D.
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
An Introduction to Part of C++ STL
An Introduction to Part of C++ STLAn Introduction to Part of C++ STL
An Introduction to Part of C++ STL
乐群 陈
 
Java Tutorial Lab 8
Java Tutorial Lab 8Java Tutorial Lab 8
Java Tutorial Lab 8
Berk Soysal
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
•sreejith •sree
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
Knoldus Inc.
 
Teach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with ScalaTeach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with Scala
Damian Jureczko
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
Dhananjay Kumar
 

Similar to Comparing Haskell & Scala (20)

Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
Martin Ockajak
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform Research
Vasil Remeniuk
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
Mohsen Zainalpour
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
Debasish Ghosh
 
Scala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectiveScala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspective
gabalese
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
Meetu Maltiar
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
Knoldus Inc.
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
Werner Hofstra
 
Meet scala
Meet scalaMeet scala
Meet scala
Wojciech Pituła
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
Tim (dev-tim) Zadorozhniy
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
romanandreg
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
Tomer Gabel
 
C# programming
C# programming C# programming
C# programming
umesh patil
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
JUG Lausanne
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
Denis
 
Ten-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala DevelopersTen-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala Developers
ihji
 
Scala jargon cheatsheet
Scala jargon cheatsheetScala jargon cheatsheet
Scala jargon cheatsheet
Ruslan Shevchenko
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
Martin Ockajak
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform Research
Vasil Remeniuk
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
Debasish Ghosh
 
Scala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectiveScala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspective
gabalese
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
Werner Hofstra
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
romanandreg
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
Tomer Gabel
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
JUG Lausanne
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
Denis
 
Ten-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala DevelopersTen-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala Developers
ihji
 
Ad

Recently uploaded (20)

Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
Buy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training techBuy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training tech
Rustici Software
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb ClarkDeploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Peter Caitens
 
GC Tuning: A Masterpiece in Performance Engineering
GC Tuning: A Masterpiece in Performance EngineeringGC Tuning: A Masterpiece in Performance Engineering
GC Tuning: A Masterpiece in Performance Engineering
Tier1 app
 
Medical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk ScoringMedical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk Scoring
ICS
 
Unit Two - Java Architecture and OOPS
Unit Two  -   Java Architecture and OOPSUnit Two  -   Java Architecture and OOPS
Unit Two - Java Architecture and OOPS
Nabin Dhakal
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
The Elixir Developer - All Things Open
The Elixir Developer - All Things OpenThe Elixir Developer - All Things Open
The Elixir Developer - All Things Open
Carlo Gilmar Padilla Santana
 
Adobe Audition Crack FRESH Version 2025 FREE
Adobe Audition Crack FRESH Version 2025 FREEAdobe Audition Crack FRESH Version 2025 FREE
Adobe Audition Crack FRESH Version 2025 FREE
zafranwaqar90
 
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studiesTroubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Tier1 app
 
NYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdfNYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdf
AUGNYC
 
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business StageA Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
SynapseIndia
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
How to Install and Activate ListGrabber Plugin
How to Install and Activate ListGrabber PluginHow to Install and Activate ListGrabber Plugin
How to Install and Activate ListGrabber Plugin
eGrabber
 
Best HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRMBest HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRM
accordHRM
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
Buy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training techBuy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training tech
Rustici Software
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb ClarkDeploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Peter Caitens
 
GC Tuning: A Masterpiece in Performance Engineering
GC Tuning: A Masterpiece in Performance EngineeringGC Tuning: A Masterpiece in Performance Engineering
GC Tuning: A Masterpiece in Performance Engineering
Tier1 app
 
Medical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk ScoringMedical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk Scoring
ICS
 
Unit Two - Java Architecture and OOPS
Unit Two  -   Java Architecture and OOPSUnit Two  -   Java Architecture and OOPS
Unit Two - Java Architecture and OOPS
Nabin Dhakal
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
Adobe Audition Crack FRESH Version 2025 FREE
Adobe Audition Crack FRESH Version 2025 FREEAdobe Audition Crack FRESH Version 2025 FREE
Adobe Audition Crack FRESH Version 2025 FREE
zafranwaqar90
 
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studiesTroubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Tier1 app
 
NYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdfNYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdf
AUGNYC
 
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business StageA Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
SynapseIndia
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
How to Install and Activate ListGrabber Plugin
How to Install and Activate ListGrabber PluginHow to Install and Activate ListGrabber Plugin
How to Install and Activate ListGrabber Plugin
eGrabber
 
Best HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRMBest HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRM
accordHRM
 
Ad

Comparing Haskell & Scala

  • 2. Martin Ockajak from Zürich Software Engineer @martin_ockajak
  • 3. Outline ● Similarities ● Conceptual differences ● Haskell – extra features ● Scala – extra features ● Practical considerations
  • 5. Overview ● High-level functional language ● Product of programming language research ● Haskell: Purely functional with strong side-effect handling ● Scala: Functional and object-oriented ● Automatic memory management ● Static type checking ● Type inference • Haskell: global, variant of Hindley-Milner • Scala: local, arguments require type annotations
  • 6. Expressions ● Everything is an expression producing a value ● No operators, only infix functions with symbolic names ● Haskell let list = [1 + 2, 3] in list !! 0 (#%) :: String -> String (#%) x = x ++ "!" ● Scala val list = List(1 + 2, 3) list(0) def #%(x: String): String = x + "!"
  • 7. Higher order functions Functions as arguments and values ● Haskell applyAndInc f x = f x + 1 double x = x * 2 applyAndInc double 3 ● Scala def applyAndInc(f: Int => Int, x: Int) = f(x) + 1 def double(x: Int): Int = x * 2 applyAndInc(double, 3)
  • 8. Anonymous functions Lambda expressions ● Haskell map (x -> x + 1) [1, 2, 3] map (+ 1) [1, 2, 3] ● Scala List(1, 2, 3) map(x => x + 1) List(1, 2, 3) map(_ + 1)List(1, 2, 3) map(x => x + 1) List(1, 2, 3) map(_ + 1) // partial function List(1, 2, "3") collect { case x: Int => x + 1 }
  • 9. Currying Partial function application ● Haskell curried x y = x + y + 1 let partial = curried 1 in partial 2 uncurried = uncurry curried curriedAgain = curry uncurried ● Scala def curried(x: Int)(y: Int): Int = x + y + 1 val partial = curried(1) _ partial(2) val uncurried = Function.uncurried(curried _) val curriedAgain = uncurried.curried
  • 10. Encapsulation Modules and access modifiers ● Haskell module Module (foo) where foo x = bar x + 1 bar x = x * 2 ● Scala object Encapsulation { def foo(x: Int) = bar(x) + 1 private def bar(x: Int) = x * 2 }
  • 11. Pattern matching with guards ● Haskell factorial 0 = 1 factorial n = n * factorial (n - 1) pattern :: [Int] -> Int pattern l | [x] <- l, x /= 0 = 1 | length l > 1 = 2 | otherwise = 0 ● Scala def factorial(n: Int): Int = n match { case 0 => 1 case n => n * factorial(n - 1) } def pattern(l: List[Int]): Int = l match { case List(x) if x != 0 => 1 case l if l.size > 1 => 1 case _ => 0 }
  • 12. List comprehensions ● Haskell [ (x, y) | x <- [1, 2, 3], y <- [4, 5, 6], x * y > 7 ] [0 | _ <- [1..10] ] ● Scala for { x <- List(1, 2, 3) y <- List(4, 5, 6) if x * y > 7 } yield (x, y) for (_ <- List(1 to 10)) yield 0
  • 13. Monadic composition notation ● Haskell do x <- [1, 2, 3] y <- [4, 5, 6] let z = (x + y) return z ● Scala for { x <- List(1, 2, 3) y <- List(4, 5, 6) z = x + y } yield z
  • 14. Type system ● Parametric polymorphism ● Ad hoc polymorphism ● Haskell: Typeclasses ● Scala: Typeclasses, method overloading, subtyping ● Generalized algebraic data types ● Multi-parameter type classes ● Functional dependencies
  • 15. Type system ● Compound types ● Type aliases ● Existential types ● Higher order types ● Kinds
  • 16. Algebraic data types ● Haskell data Tree a = Empty | Node a (Tree a) (Tree a) ● Scala sealed trait Tree[A] case class Empty[A]() extends Tree[A] case class Node[A](value: A, left: Tree[A], right: Tree[A]) extends Tree[A]
  • 17. Typeclasess ● Haskell class Equals a where eq :: a -> a -> Bool instance Equals Integer where eq x y = x == y tcEquals :: (Equals a) => a -> a -> Bool tcEquals a b = eq a b ● Scala trait Equals[T] { def eq(x: T, y: T): Boolean } implicit object EqualsInt extends Equals[Int] { override def eq(x: Int, y: Int): Boolean = x == y } def tcEquals[T: Equals](x: T, y: T): Boolean = implicitly[Equals[T]].eq(x, y)
  • 18. Additional features ● Implicit parameters ● Annotations ● Compile-time metaprogramming ● Haskell: Template Haskell ● Scala: Macros
  • 20. Purity ● Haskell ● Referential transparency ● Side effects modeled via monads ● Functions are pure ● Scala ● No referential transparency guarantees ● Side effects allowed anywhere ● Functions cannot be considered pure
  • 21. Default evaluation strategy ● Haskell ● Non-strict lazy evaluation ● Optional eager evaluation ● Bang patterns ● Strict modules ● Scala ● Strict eager evaluation ● Optional lazy evaluation ● Call-by-name parameter with lazy val pattern
  • 22. Control flow ● Haskell ● Completely declarative ● Exception handling via monads ● No way to jump off current scope ● Scala ● Imperative constructs are supported ● Exception handling at language level ● Early return from a method
  • 23. Haskell – extra features
  • 24. Pointfree style ● Omitting arguments in function definition -- Point-wise incp x = x + 1 expp x = 1 + 2 * x -- Pointfree incf = (+ 1) expf = (1 +) . (2 *)
  • 25. Polymorphic string literals ● String syntax for various string-like types string1 :: String string1 = "string" string2 :: Text string2 = "text" "test" :: IsString a => a class IsString a where fromString :: String -> a
  • 26. Extended list comprehensions ● Parallel (zip) [ (x, y) | x <- [1, 2, 3] | y <- [4, 5, 6]] ● Transform cities = [ ("Berlin", 4.1), ("Milan", 5.2), ("Zurich", 1.3) ] [ name ++ "!" | (name, size) <- cities, then sortWith by size, then drop 1 ] ● Monad [ x + y | x <- Just 1, y <- Just 2 ]
  • 27. Deriving typeclass instances ● Typeclasses: Eq, Ord, Enum, Bounded, Show, Read data Coordinate = Planar Float Float | Spatial Float Float Float deriving (Eq, Ord, Show) Planar 1 2 == Planar 1 2 Spatial 1 2 1 < Spatial 1 2 3 show (Planar 1 2)
  • 28. Higher rank polymorphism ● Polymorphic function argument specified by the callee id :: a -> a id x = x rank1 :: forall a. a -> a rank1 x = x rank2 :: (forall a. Num a => a -> a) -> (Int, Float) rank2 f = (f 1, f 1.0) rank2 (* 2)
  • 29. Compiler extensions ● View patterns & pattern synonyms ● Type families ● Data type generic programming ● Kind polymorphism ● And many more …
  • 30. Scala – extra features
  • 31. Imperative programming ● Mutable state ● Code blocks ● While loops var mutable = 1 mutable = 2 while (mutable < 3) { List(1, 2, 3).foreach(_ => println("Missile fired")) mutable += 1 } throw new IllegalStateException("Abandon ship")
  • 32. Object-oriented programming ● Subtyping ● Type variance, type bounds ● Class-based inheritance system ● Classes, traits, objects, abstract type members ● Mixin class composition ● Multiple inheritance with traits, self-typed references
  • 33. Named and default arguments ● Just like in Python def very(standard: String, default: String = "value"): Unit = () very("text") def handy(default: String = "value", standard: String): Unit = () handy(standard = "text")
  • 34. String interpolation ● Programmable via custom interpolators val neat = 7 // standard library val substitution = s"Is $neat" val printf = f"Number is $neat%02d" val noEscaping = raw"somenthing" // external library val document = json"""{ "hello": "world" }"""
  • 35. Flexible scoping ● Fields in traits ● Abstract members ● Nested function definitions ● Multiple classes & objects in one source file trait FlexibleScoping { def abstractMethod(text: String): String val abstractField: Int def get: String = { def compute: String = "result" abstractMethod(compute) } }
  • 36. Implicit conversion ● Automated conversion of method arguments ● Searches in current and various outer scopes ● Method argument is converted using the implicit method def more(value: Int): Int = 2 * value implicit def convert(value: Vector[_]): Int = value.size more(Vector(1, 2, 3)) // equivalent call with explicit conversion more(convert(Vector(1, 2, 3)))
  • 37. Structural typing ● Type checking based on type contents not its name ● Resolved at compile-time as opposed to duck-typing def oneMore(countable: { def size: Int }): Unit = { countable.size + 1 } oneMore(List(1, 2, 3))
  • 38. Dynamic typing ● Programmable late binding at run-time import scala.language.dynamics object Accepts extends Dynamic { def selectDynamic(name: String): Int = name.size def applyDynamic(name: String)(args: Any*): String = name } Accepts.something Accepts.hello("World")
  • 39. Type system features ● Type lambdas ● F-bounded types ● Self-recursive types ● Path-dependent types ● Instance bound types ● Value classes ● Type specialization
  • 41. Practicality - Haskell ● Great productivity ● High runtime performance ● Clever community ● Solid library and tooling ecosystem ● Reasoning about can be tricky ● Steep learning curve (real or imagined)
  • 42. Practicality - Scala ● Great productivity ● High runtime performance ● Clever community ● Largest library and tooling ecosystem ● Easy to transition from Java, C++, C# ● Java interoperability somewhat pollutes the language
  翻译: