SlideShare a Scribd company logo
1 of 32
Arrow 101 - Kotlin
funcional com Arrow
Conceitos sobre teoria da categoria e programação
funcional em Kotlin.
Leandro Borges Ferreira
FP é sobre compor funções
fun greaterThanTenAndEven: (List<Int>) -> List<Int> =
{ list -> list.filter { num -> num > 3 && num % 2 == 0} }
Podemos melhorar
val greaterThanTen = { num : Int -> num > 3}
val even = { num : Int -> num % 2 == 0 }
val greaterThanTenAndEven : (Int) -> Boolean =
{ num -> greaterThanTen(num) && even(num) }
listOf<Int>().filter(greaterThanTenAndEven)
Funções parcialmente aplicadas
val filter: ((Int) -> Boolean, List<Int>) -> List<Int> =
{ f, list -> list.filter { num -> f(num) } }
val takeEvens = filter.partially1 { num -> num % 2 == 0 }
val takeGreaterThanTen = filter.partially1 { num -> num > 10 }
val takeEvensGreaterThanTen = takeEvens compose takeGreaterThanTen
//[1, 2, 5, 12] -> takeEvens -> [2, 12] -> takeGreaterThanTen -> [12]
takeEvensGreaterThanTen(listOf(1, 5, 12)) // Result: 12
Currying
val curriedFilter = filter.curried()
val takeEvens = curriedFilter({ num -> num % 2 == 0 })
val greaterThanTen = curriedFilter { num -> num > 10 }
val takeEvensGreaterThanTen = takeEvens compose greaterThanTen
DataTypes
val numOp : Option<Int> = Some(3)
numOp.map { num -> num + 3 }
numOp.getOrElse { throw Exception("Ops!") }
val none : Option<Int> = None
val num : Int? = 3
num?.plus(3)
num ?: throw Exception("Ops!")
Option
Try
Try<String> {
throw Exception("Boom!")
}.fold({ throwable ->
println("Vish!")
}, { string ->
println("Tudo certo!")
})
Either
val right: Either<String, Int> = Either.Right(5)
val left: Either<String, Int> =
Either.Left(“Putz, deu errado”)
val right: Either<String, Int> = 5.right()
either.fold({
//If left
}, {
//If right
})
Teoria da Categoria
Bolinhas conectadas por setinhas
Teoria da Categoria é a ciência da abstração e composição
Dr. Eugenia Cheng
Composição de função
Monoids
Monoids - Arrow
@typeclass
interface Monoid<A> : TC {
fun empty(): A
fun combine(a: A, b: A): A
}
data class Color(val red: Int = 0,
val green: Int = 0,
val blue: Int = 0) {
companion object
}
Monoid
@instance(Color::class)
interface ColorMonoid: Monoid<Color> {
override fun empty(): Color = Color()
override fun combine(a: Color, b: Color): Color = Color(
red = min(a.red + b.red, 255),
green = min(a.green + b.green, 255),
blue = min(a.blue + b.blue, 255))
}
Color.monoid().run { Color() + Color() }
Option + Monoids
val numOp1 = Some(3)
val numOp2 = Some(5)
val numOp3 = Option.monoid(Int.monoid())
.run { numOp1 + numOp2 }
// numOp3 = Some(5)
Tipos de ordem maior
val stringList : List<String>
val list : List<A>
val stringA = A<String>
val aOfB = A<B>
Kind<A, B> = A<B>
Functors
interface Functor<F> {
fun <A, B> Kind<F, A>.map(f: (A) -> B): Kind<F, B>
fun <A, B> lift(f: (A) -> B): (Kind<F, A>) -> Kind<F, B> =
{ fa: Kind<F, A> ->
fa.map(f)
}
}
Você já usa Functors
val stringList : List<String> = listOf()
val intList = stringList.map { word -> word.toInt() }
val floatList = intList.map { int -> int.toFloat() }
fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R>
fun <A, B> Kind<F, A>.map(f: (A) -> B): Kind<F, B>
Iterables em Kotlin se comportam como Functors
Compare as assinaturas
F<A> -> F<B>
Tudo pode ser mapeável
val eitherString: Either<Exception, String> = "either".right()
val eitherInt: Either<Exception, Int> =
eitherString.map { word -> word.toInt() }
val tryString : Try<String> = Try { "try!" }
val tryInt : Try<Int> = tryString.map { word -> word.toInt() }
val optionInt : Option<Int> =
Option.just("option").map { word -> word.toInt() }
Applicative
Aplica funções nos contêineres
Just:
fun <A> just(a: A): Kind<F, A>
fun <A> just(a: A): Option<A> = Option.just(a)
Exemplo
Applicative
Aplica funções nos contêineres
Ap:
fun <A, B> Kind<F, A>
.ap(ff: Kind<F, (A) -> B>): Kind<F, B>
Exemplo
val opFn : Option<(String)-> Int> = Option.just { word -> word.toInt() }
val opFnInt : Option<Int> = Option.just("String").ap(opFn)
Applicative Builder
val tuple = Option.applicative()
.tupled(
Option.just("First"),
Option.just("Second")
)
val map : Map<String, String> = mapOf()
val opWord1 = map["id1"].toOption()
val opWord2 = map["id2"].toOption()
Option.applicative()
.tupled(opWord1, opWord2)
.fix()
.map { (word1, word2) ->
//Só entro aqui se os dois possuem valor
}
Monads
Retirar um wrapper dentro de outro
Ilustração do flatMap()
Você já usa Monads
val intList : List<Int> = listOf<String>().flatMap {
listOf<Int>()
}
val intList2 : List<List<Int>> = listOf<String>().map {
listOf<Int>()
}
val intList2Flat : List<Int> = intList2.flatten()
Programar pensando nos
Wrappers
val sum10 : (Int) -> Int = { num : Int -> num + 10 }
val multBy5 : (Int) -> Int = { num : Int -> num * 5 }
val sum10MultBy5 : (Int) -> Int = multBy5 compose sum10
val numList : List<Int> = listOf()
numList.map { num -> sum10MultBy5(num) }
Programar pensando nos
Wrappers
val sum10 : (Int) -> Int = { num : Int -> num + 10 }
val multBy5 : (Int) -> Int = { num : Int -> num * 5 }
val sum10MultBy5 : (Int) -> Int = multBy5 compose sum10
fun <A> fnWithWrapper(fu: Functor<A>)
: (Kind<A, Int>) -> Kind<A, Int> = fu.lift { sum10MultBy5(it) }
val opFn = fnWithWrapper(Option.functor())
val result1 : Option<Int> = opFn(Option.just(5)).fix()
//Some(75)
val eiFn = fnWithWrapper(Either.functor<Exception>())
val result2 : Either<Exception, Int> = eiFn(Either.right(5)).fix()
//Right(75)
val listFn = fnWithWrapper(ListK.functor())
val result3 : ListK<Int> = listFn(listOf(5).k()).fix()
//ListK(75)
val obs = Observable.fromArray(1,2,3,4,5).k()
val obsFn = fnWithWrapper(ObservableK.functor())
val result4 : ObservableK<Int> = obsFn(obs).fix()
Monad Comprehensions
As vezes flatMaps ficam bem difíceis de se ler…
fun command() : Either<Nothing, List<String>>
val either: Either<Nothing, List<String>> =
command1().flatMap { result1 ->
command2(result1).flatMap { result2 ->
command3(result2).flatMap {
Either.right(listOf(“ok!"))
}
}
}
Monad Comprehensions
Comprehensions deixam o código mais “Flat"
fun command() : Either<Nothing, List<String>>
val eitherC: Either<Nothing, List<String>> =
Either.monad<Nothing>().binding {
val result1 = command1().bind()
val result2 = command2().bind()
val result3 = command3().bind()
result3
}.fix()
Monad Comprehensions
Comprehensions deixam o código mais “Flat"
fun command() : Either<Nothing, List<String>>
val eitherC: Either<Nothing, List<String>> =
Either.monad<Nothing>().binding {
val result1 = command1().bind()
val result2 = command2().bind()
val result3 = command3().bind()
result3
}.fix()
Obrigado Pessoal!

More Related Content

What's hot

machine learning code
machine learning codemachine learning code
machine learning codeAmir Shokri
 
An introduction to functional programming with go
An introduction to functional programming with goAn introduction to functional programming with go
An introduction to functional programming with goEleanor McHugh
 
(Fun)ctional go
(Fun)ctional go(Fun)ctional go
(Fun)ctional goBenJanecke
 
Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Luka Jacobowitz
 
Excel function
Excel functionExcel function
Excel functionSirajRock
 
20180310 functional programming
20180310 functional programming20180310 functional programming
20180310 functional programmingChiwon Song
 
Fp in scala with adts
Fp in scala with adtsFp in scala with adts
Fp in scala with adtsHang Zhao
 
Principled Error Handling with FP
Principled Error Handling with FPPrincipled Error Handling with FP
Principled Error Handling with FPLuka Jacobowitz
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them AllJohn De Goes
 
Exploring slides
Exploring slidesExploring slides
Exploring slidesakaptur
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverseLuka Jacobowitz
 
20181020 advanced higher-order function
20181020 advanced higher-order function20181020 advanced higher-order function
20181020 advanced higher-order functionChiwon Song
 
Testing in the World of Functional Programming
Testing in the World of Functional ProgrammingTesting in the World of Functional Programming
Testing in the World of Functional ProgrammingLuka Jacobowitz
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoidsLuka Jacobowitz
 
Code sources des fonctions table cp
Code sources des fonctions table cpCode sources des fonctions table cp
Code sources des fonctions table cpidhem110
 
C tech questions
C tech questionsC tech questions
C tech questionsvijay00791
 
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonByterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonakaptur
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collectionsMyeongin Woo
 

What's hot (20)

machine learning code
machine learning codemachine learning code
machine learning code
 
An introduction to functional programming with go
An introduction to functional programming with goAn introduction to functional programming with go
An introduction to functional programming with go
 
(Fun)ctional go
(Fun)ctional go(Fun)ctional go
(Fun)ctional go
 
Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020
 
Excel function
Excel functionExcel function
Excel function
 
20180310 functional programming
20180310 functional programming20180310 functional programming
20180310 functional programming
 
Fp in scala with adts
Fp in scala with adtsFp in scala with adts
Fp in scala with adts
 
Principled Error Handling with FP
Principled Error Handling with FPPrincipled Error Handling with FP
Principled Error Handling with FP
 
ProgrammingwithGOLang
ProgrammingwithGOLangProgrammingwithGOLang
ProgrammingwithGOLang
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them All
 
Functor Laws
Functor LawsFunctor Laws
Functor Laws
 
Exploring slides
Exploring slidesExploring slides
Exploring slides
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverse
 
20181020 advanced higher-order function
20181020 advanced higher-order function20181020 advanced higher-order function
20181020 advanced higher-order function
 
Testing in the World of Functional Programming
Testing in the World of Functional ProgrammingTesting in the World of Functional Programming
Testing in the World of Functional Programming
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoids
 
Code sources des fonctions table cp
Code sources des fonctions table cpCode sources des fonctions table cp
Code sources des fonctions table cp
 
C tech questions
C tech questionsC tech questions
C tech questions
 
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonByterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collections
 

Similar to Arrow 101 - Kotlin funcional com Arrow

Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기진성 오
 
Use Applicative where applicable!
Use Applicative where applicable!Use Applicative where applicable!
Use Applicative where applicable!Hermann Hueck
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to SwiftGiordano Scalzo
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
The Arrow Library in Kotlin
The Arrow Library in KotlinThe Arrow Library in Kotlin
The Arrow Library in KotlinGarth Gilmour
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingSaurabh Singh
 
Swift Rocks #2: Going functional
Swift Rocks #2: Going functionalSwift Rocks #2: Going functional
Swift Rocks #2: Going functionalHackraft
 
Monadologie
MonadologieMonadologie
Monadologieleague
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиMaxim Kulsha
 
Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.Python Meetup
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patternsleague
 
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...PROIDEA
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptxYagna15
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Mattersromanandreg
 
Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in ScalaKnoldus Inc.
 

Similar to Arrow 101 - Kotlin funcional com Arrow (20)

Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
Use Applicative where applicable!
Use Applicative where applicable!Use Applicative where applicable!
Use Applicative where applicable!
 
Map, Reduce and Filter in Swift
Map, Reduce and Filter in SwiftMap, Reduce and Filter in Swift
Map, Reduce and Filter in Swift
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
The Arrow Library in Kotlin
The Arrow Library in KotlinThe Arrow Library in Kotlin
The Arrow Library in Kotlin
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional Programming
 
Swift Rocks #2: Going functional
Swift Rocks #2: Going functionalSwift Rocks #2: Going functional
Swift Rocks #2: Going functional
 
Monadologie
MonadologieMonadologie
Monadologie
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
 
Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
 
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in Scala
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
 

Recently uploaded

College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 

Recently uploaded (20)

College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 

Arrow 101 - Kotlin funcional com Arrow

  • 1. Arrow 101 - Kotlin funcional com Arrow Conceitos sobre teoria da categoria e programação funcional em Kotlin. Leandro Borges Ferreira
  • 2.
  • 3. FP é sobre compor funções fun greaterThanTenAndEven: (List<Int>) -> List<Int> = { list -> list.filter { num -> num > 3 && num % 2 == 0} }
  • 4. Podemos melhorar val greaterThanTen = { num : Int -> num > 3} val even = { num : Int -> num % 2 == 0 } val greaterThanTenAndEven : (Int) -> Boolean = { num -> greaterThanTen(num) && even(num) } listOf<Int>().filter(greaterThanTenAndEven)
  • 5. Funções parcialmente aplicadas val filter: ((Int) -> Boolean, List<Int>) -> List<Int> = { f, list -> list.filter { num -> f(num) } } val takeEvens = filter.partially1 { num -> num % 2 == 0 } val takeGreaterThanTen = filter.partially1 { num -> num > 10 } val takeEvensGreaterThanTen = takeEvens compose takeGreaterThanTen //[1, 2, 5, 12] -> takeEvens -> [2, 12] -> takeGreaterThanTen -> [12] takeEvensGreaterThanTen(listOf(1, 5, 12)) // Result: 12
  • 6. Currying val curriedFilter = filter.curried() val takeEvens = curriedFilter({ num -> num % 2 == 0 }) val greaterThanTen = curriedFilter { num -> num > 10 } val takeEvensGreaterThanTen = takeEvens compose greaterThanTen
  • 7. DataTypes val numOp : Option<Int> = Some(3) numOp.map { num -> num + 3 } numOp.getOrElse { throw Exception("Ops!") } val none : Option<Int> = None val num : Int? = 3 num?.plus(3) num ?: throw Exception("Ops!") Option
  • 8. Try Try<String> { throw Exception("Boom!") }.fold({ throwable -> println("Vish!") }, { string -> println("Tudo certo!") })
  • 9. Either val right: Either<String, Int> = Either.Right(5) val left: Either<String, Int> = Either.Left(“Putz, deu errado”) val right: Either<String, Int> = 5.right() either.fold({ //If left }, { //If right })
  • 10. Teoria da Categoria Bolinhas conectadas por setinhas Teoria da Categoria é a ciência da abstração e composição Dr. Eugenia Cheng
  • 11.
  • 13.
  • 15. Monoids - Arrow @typeclass interface Monoid<A> : TC { fun empty(): A fun combine(a: A, b: A): A } data class Color(val red: Int = 0, val green: Int = 0, val blue: Int = 0) { companion object }
  • 16. Monoid @instance(Color::class) interface ColorMonoid: Monoid<Color> { override fun empty(): Color = Color() override fun combine(a: Color, b: Color): Color = Color( red = min(a.red + b.red, 255), green = min(a.green + b.green, 255), blue = min(a.blue + b.blue, 255)) } Color.monoid().run { Color() + Color() }
  • 17. Option + Monoids val numOp1 = Some(3) val numOp2 = Some(5) val numOp3 = Option.monoid(Int.monoid()) .run { numOp1 + numOp2 } // numOp3 = Some(5)
  • 18. Tipos de ordem maior val stringList : List<String> val list : List<A> val stringA = A<String> val aOfB = A<B> Kind<A, B> = A<B>
  • 19. Functors interface Functor<F> { fun <A, B> Kind<F, A>.map(f: (A) -> B): Kind<F, B> fun <A, B> lift(f: (A) -> B): (Kind<F, A>) -> Kind<F, B> = { fa: Kind<F, A> -> fa.map(f) } }
  • 20. Você já usa Functors val stringList : List<String> = listOf() val intList = stringList.map { word -> word.toInt() } val floatList = intList.map { int -> int.toFloat() } fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> fun <A, B> Kind<F, A>.map(f: (A) -> B): Kind<F, B> Iterables em Kotlin se comportam como Functors Compare as assinaturas F<A> -> F<B>
  • 21. Tudo pode ser mapeável val eitherString: Either<Exception, String> = "either".right() val eitherInt: Either<Exception, Int> = eitherString.map { word -> word.toInt() } val tryString : Try<String> = Try { "try!" } val tryInt : Try<Int> = tryString.map { word -> word.toInt() } val optionInt : Option<Int> = Option.just("option").map { word -> word.toInt() }
  • 22. Applicative Aplica funções nos contêineres Just: fun <A> just(a: A): Kind<F, A> fun <A> just(a: A): Option<A> = Option.just(a) Exemplo
  • 23. Applicative Aplica funções nos contêineres Ap: fun <A, B> Kind<F, A> .ap(ff: Kind<F, (A) -> B>): Kind<F, B> Exemplo val opFn : Option<(String)-> Int> = Option.just { word -> word.toInt() } val opFnInt : Option<Int> = Option.just("String").ap(opFn)
  • 24. Applicative Builder val tuple = Option.applicative() .tupled( Option.just("First"), Option.just("Second") ) val map : Map<String, String> = mapOf() val opWord1 = map["id1"].toOption() val opWord2 = map["id2"].toOption() Option.applicative() .tupled(opWord1, opWord2) .fix() .map { (word1, word2) -> //Só entro aqui se os dois possuem valor }
  • 25. Monads Retirar um wrapper dentro de outro Ilustração do flatMap()
  • 26. Você já usa Monads val intList : List<Int> = listOf<String>().flatMap { listOf<Int>() } val intList2 : List<List<Int>> = listOf<String>().map { listOf<Int>() } val intList2Flat : List<Int> = intList2.flatten()
  • 27. Programar pensando nos Wrappers val sum10 : (Int) -> Int = { num : Int -> num + 10 } val multBy5 : (Int) -> Int = { num : Int -> num * 5 } val sum10MultBy5 : (Int) -> Int = multBy5 compose sum10 val numList : List<Int> = listOf() numList.map { num -> sum10MultBy5(num) }
  • 28. Programar pensando nos Wrappers val sum10 : (Int) -> Int = { num : Int -> num + 10 } val multBy5 : (Int) -> Int = { num : Int -> num * 5 } val sum10MultBy5 : (Int) -> Int = multBy5 compose sum10 fun <A> fnWithWrapper(fu: Functor<A>) : (Kind<A, Int>) -> Kind<A, Int> = fu.lift { sum10MultBy5(it) } val opFn = fnWithWrapper(Option.functor()) val result1 : Option<Int> = opFn(Option.just(5)).fix() //Some(75) val eiFn = fnWithWrapper(Either.functor<Exception>()) val result2 : Either<Exception, Int> = eiFn(Either.right(5)).fix() //Right(75) val listFn = fnWithWrapper(ListK.functor()) val result3 : ListK<Int> = listFn(listOf(5).k()).fix() //ListK(75) val obs = Observable.fromArray(1,2,3,4,5).k() val obsFn = fnWithWrapper(ObservableK.functor()) val result4 : ObservableK<Int> = obsFn(obs).fix()
  • 29. Monad Comprehensions As vezes flatMaps ficam bem difíceis de se ler… fun command() : Either<Nothing, List<String>> val either: Either<Nothing, List<String>> = command1().flatMap { result1 -> command2(result1).flatMap { result2 -> command3(result2).flatMap { Either.right(listOf(“ok!")) } } }
  • 30. Monad Comprehensions Comprehensions deixam o código mais “Flat" fun command() : Either<Nothing, List<String>> val eitherC: Either<Nothing, List<String>> = Either.monad<Nothing>().binding { val result1 = command1().bind() val result2 = command2().bind() val result3 = command3().bind() result3 }.fix()
  • 31. Monad Comprehensions Comprehensions deixam o código mais “Flat" fun command() : Either<Nothing, List<String>> val eitherC: Either<Nothing, List<String>> = Either.monad<Nothing>().binding { val result1 = command1().bind() val result2 = command2().bind() val result3 = command3().bind() result3 }.fix()