It's All About Morphisms

Total Page:16

File Type:pdf, Size:1020Kb

It's All About Morphisms It’s All About Morphisms Uberto Barbini @ramtop https://medium.com/@ramtop About me OOP programmer Agile TDD Functional PRogramming Finance Kotlin Industry Blog: https://medium.com/@ ramtop Twitter: @ramtop #morphisms#VoxxedVienna @ramtop Map of this presentation Monoid Category Monad Functor Natural Transformation Yoneda Applicative Morphisms all the way down... #morphisms#VoxxedVienna @ramtop I don’t care about Monads, why should I? Neither do I what I care about is y el is to define system behaviour ec Pr #morphisms#VoxxedVienna @ramtop This presentation will be a success if most of you will not fall asleep #morphisms#VoxxedVienna @ramtop This presentation will be a success if You will consider that Functional Programming is about transformations and preserving properties. Not (only) lambdas and flatmap #morphisms#VoxxedVienna @ramtop What is this Category thingy? Invented in 1940s “with the goal of understanding the processes that preserve mathematical structure.” “Category Theory is about relation between things” “General abstract nonsense” #morphisms#VoxxedVienna @ramtop Once upon a time there was a Category of Stuffed Toys and a Category of Tigers... #morphisms#VoxxedVienna @ramtop A Category is defined in 5 steps: 1) A collection of Objects #morphisms#VoxxedVienna @ramtop A Category is defined in 5 steps: 2) A collection of Arrows #morphisms#VoxxedVienna @ramtop A Category is defined in 5 steps: 3) Each Arrow works on 2 Objects #morphisms#VoxxedVienna @ramtop A Category is defined in 5 steps: 4) Arrows can be combined #morphisms#VoxxedVienna @ramtop A Category is defined in 5 steps: 5) Each Object has an Identity (an arrow pointing to itself) #morphisms#VoxxedVienna @ramtop #morphisms#VoxxedVienna @ramtop A Category Example Tube Map: Objects → stations stations Arrows → stations travel routes Each Arrows connect 2 stations Arrow composition is travelling along the line Identity Arrow is staying in the same station #morphisms#VoxxedVienna @ramtop London Tube Category #morphisms#VoxxedVienna @ramtop Monoid Category Monad Functor Natural Transformation Yoneda Applicative This presentation is a Category as well! #morphisms#VoxxedVienna @ramtop AddItem Ready NewOrder Dispatch Dispatched Cancel Close Return Cancelled Closed Returned Event Source Category https://skillsmatter.com/skillscasts/11486-functional-cqrs #morphisms#VoxxedVienna @ramtop Functional Programming is also a Category Each programming language has a Category: Types are the objects and Functions are the morphisms. Partial functions don’t have a defined return for all inputs. In reality all programming functions are partial: they can raise Exceptions or never end. They always have an hidden return of Bottom Type (⊥)) #morphisms#VoxxedVienna @ramtop Change of mindset! Object Oriented Functional Living Bacteria Gears and Pipes Opaque Transparent Hidden State Immutable State Interfaces Type Classes #morphisms#VoxxedVienna @ramtop Kotlin for functional programming ● Nullable and not-nullable types ● Type Aliases ● Class extensions ● Tail recursion ● Pattern matching (when) ● Arrow-kt bindinds with coroutines ● Arrow-kt Typeclasses (?) #morphisms#VoxxedVienna @ramtop arrow-kt.io #morphisms#VoxxedVienna @ramtop KEEP-87 TypeClasses #morphisms#VoxxedVienna @ramtop Purity and Immutability For the Category morphisms to work in programming we need Purity and Immutability. But they are not a goal per se, only a necessity for the main goal: composition and transformation. Ultimately everything is converted in assembly which is neither pure nor immutable. We need those quality only for exposed code #morphisms#VoxxedVienna @ramtop Monoid What about the category of morphisms of a category? Are they composable? It’s a Category with a single Object and lots of Morphisms A Category with only one Object is a Monoid #morphisms#VoxxedVienna @ramtop #morphisms#VoxxedVienna @ramtop Programming with Monoids A type class with two methods combine → stations monoid append empty → stations neutral element (x <> y) <> z = x <> (y <> z) -- associativity empty <> x = x -- left identity x <> empty = x -- right identity #morphisms#VoxxedVienna @ramtop Generics Type Contructors List<A> is just an abstract type to build List<Int> List<String> List<User> etc. #morphisms#VoxxedVienna @ramtop Type Class vs Interface ● Interfaces “unify” different types: Cat and Dogs can be treated as Animals ● Type Classes “group” types with similar behaviour, without hiding their types: Cats and Dogs can both form couples but cats can mate only with cats and dogs with dogs. You cannot represent that with interfaces. #morphisms#VoxxedVienna @ramtop Typeclass Instances ● Typeclasses work with instances (like a singleton) ● List is not a Monoid nor a Functor nor a Monad but it has an (or more) instance of Monoid one of Functor and one of Monad ● Technically we implement instances as an interface with a singletons specific implementation. ● We can have different implementation for difference in evaluation, for example because of concurrency #morphisms#VoxxedVienna @ramtop Enough talk, let’s see the code! Monoid TypeClass Instances... ...Give us the combine extension function #morphisms#VoxxedVienna @ramtop The future (?) extension interface Monoid<T> { infix fun T.add(t: T): T } extension object IntMonoid: Monoid<Int> { inline fun Int.add(t: Int) = this + t } inline fun <T> sum(t1: T, t2: T, t3: T, with Monoid<T>) = t1 add t2 add t3 fun main() { sum(1, 2, 3) //no boxing because of inlining } #morphisms#VoxxedVienna @ramtop Transformers a.k.a. Functors #morphisms#VoxxedVienna#morphisms Very Important!! @ramtop Functors Functors can map both objects (types) and morphism (functions) between two categories Functors map must preserve the structure and some properties But can also work inside the same category (Endofunctors) #morphisms#VoxxedVienna @ramtop Functor Laws Functor is a TypeClass with a Map function that works like this. Id is the identity function. map id x = x map (g <> f) = map g <> map f) Passing the ID function must return the original value Map must honour associativity of two functions #morphisms#VoxxedVienna @ramtop #morphisms#VoxxedVienna @ramtop Try Functor Keep a context and Map operation on `it Failure without Exception #morphisms#VoxxedVienna @ramtop Functors are also Forklifts Lift a function from A --> B to F<A> --> F<B> val lifted = Try.functor().lift {x:String -> x.toInt()} lifted(Try.Success("42")) //Try.Success(42) #morphisms#VoxxedVienna @ramtop Yoneda Lemma Yoneda's lemma concerns functors from a fixed category C to the category of sets, Set. If C is a locally small category (i.e. the hom- sets are actual sets and not proper classes), then each object A of C gives rise to a natural functor to Set called a hom-functor. #morphisms#VoxxedVienna @ramtop Yoneda Lemma F<?>.map(A→B): F<B> (? must be A) The actual implementation is useful to compose of mappings without executing until we decide combine all the maps in one and then apply it. No copies of List #morphisms#VoxxedVienna @ramtop Natural Transformations A natural transformation provides a way of transforming one functor into another while respecting the internal structure of the categories involved. Transforming Data → Functions Transforming Functions → Functors Transforming Functors → Natural Transformations #morphisms#VoxxedVienna @ramtop Natural Transformations #morphisms#VoxxedVienna @ramtop Natural Transformations val list = Try {"3".toInt()}.toOption().toList() //[3] val fail = Try {"xyz".toInt()}.toOption().toList() //[] #morphisms#VoxxedVienna @ramtop Combining Functors We can imagine 2 ways to combine 2 functors F + F = F F<f> map F<a> = F<f(a)> or F * F = F flatmap (a → F<a → F<a>>) = F a #morphisms#VoxxedVienna @ramtop Applicative Functors ● We can combine a value inside a Functor with a function inside another Functor ● If the function want more than 1 param, it will return a function with x-1 params. ● Applicative can apply: ● F<A> applied to F<A->B> to create F<B> #morphisms#VoxxedVienna @ramtop Try Applicative Functor Silly example of function that can raise an Exception Exception raised! #morphisms#VoxxedVienna @ramtop The M word... ● What about a category of (endo)functors? ● Some functors have a monoid instance, others not. ● How can we call the Category of Endofunctors with a Monoid instance? A Monad is just a Monoid in the category of Endofunctors, what's the problem? #morphisms#VoxxedVienna @ramtop Monad Recipe #morphisms#VoxxedVienna @ramtop Monads Allow Sequences of Instructions #morphisms#VoxxedVienna @ramtop Monads Binding From here: val university: IO<University> = getStudent("John Smith").flatMap { student -> getUniversity(student.universityId).flatMap { university -> getDean(university.deanId) } } To here: val university: IO<University> = IO.monad().binding { val student = getStudent("John Smith").bind() val university = getUniversity(student.universityId).bind() val dean = getDean(university.deanId).bind() dean } #morphisms#VoxxedVienna @ramtop Functional Programming Dilemma: Perfectly Pure Programs are Perfectly Useless Enter Ef fects #morphisms#VoxxedVienna @ramtop Dependency Injection courtesy of Reader Monad fun getUser(userId:String):Reader<Context, User> { fun getCommonFriends(u1: User, u2: User): Reader<Context, List<User>> What’s happen if user cannot be fetched? Runs here #morphisms#VoxxedVienna @ramtop Monads Zoo ● Option All Monads are also Functors and ● Try Applicative, but the opposite is not true. ● List Each Monad as it’s specific logic on top ● Either of the Monads Laws ● Reader These
Recommended publications
  • Causal Commutative Arrows Revisited
    Causal Commutative Arrows Revisited Jeremy Yallop Hai Liu University of Cambridge, UK Intel Labs, USA [email protected] [email protected] Abstract init which construct terms of an overloaded type arr. Most of the Causal commutative arrows (CCA) extend arrows with additional code listings in this paper uses these combinators, which are more constructs and laws that make them suitable for modelling domains convenient for defining instances, in place of the notation; we refer such as functional reactive programming, differential equations and the reader to Paterson (2001) for the details of the desugaring. synchronous dataflow. Earlier work has revealed that a syntactic Unfortunately, speed does not always follow succinctness. Al- transformation of CCA computations into normal form can result in though arrows in poetry are a byword for swiftness, arrows in pro- significant performance improvements, sometimes increasing the grams can introduce significant overhead. Continuing with the ex- speed of programs by orders of magnitude. In this work we refor- ample above, in order to run exp, we must instantiate the abstract mulate the normalization as a type class instance and derive op- arrow with a concrete implementation, such as the causal stream timized observation functions via a specialization to stream trans- transformer SF (Liu et al. 2009) that forms the basis of signal func- formers to demonstrate that the same dramatic improvements can tions in the Yampa domain-specific language for functional reactive be achieved without leaving the language. programming (Hudak et al. 2003): newtype SF a b = SF {unSF :: a → (b, SF a b)} Categories and Subject Descriptors D.1.1 [Programming tech- niques]: Applicative (Functional) Programming (The accompanying instances for SF , which define the arrow operators, appear on page 6.) Keywords arrows, stream transformers, optimization, equational Instantiating exp with SF brings an unpleasant surprise: the reasoning, type classes program runs orders of magnitude slower than an equivalent pro- gram that does not use arrows.
    [Show full text]
  • What I Wish I Knew When Learning Haskell
    What I Wish I Knew When Learning Haskell Stephen Diehl 2 Version This is the fifth major draft of this document since 2009. All versions of this text are freely available onmywebsite: 1. HTML Version ­ http://dev.stephendiehl.com/hask/index.html 2. PDF Version ­ http://dev.stephendiehl.com/hask/tutorial.pdf 3. EPUB Version ­ http://dev.stephendiehl.com/hask/tutorial.epub 4. Kindle Version ­ http://dev.stephendiehl.com/hask/tutorial.mobi Pull requests are always accepted for fixes and additional content. The only way this document will stayupto date and accurate through the kindness of readers like you and community patches and pull requests on Github. https://github.com/sdiehl/wiwinwlh Publish Date: March 3, 2020 Git Commit: 77482103ff953a8f189a050c4271919846a56612 Author This text is authored by Stephen Diehl. 1. Web: www.stephendiehl.com 2. Twitter: https://twitter.com/smdiehl 3. Github: https://github.com/sdiehl Special thanks to Erik Aker for copyediting assistance. Copyright © 2009­2020 Stephen Diehl This code included in the text is dedicated to the public domain. You can copy, modify, distribute and perform thecode, even for commercial purposes, all without asking permission. You may distribute this text in its full form freely, but may not reauthor or sublicense this work. Any reproductions of major portions of the text must include attribution. The software is provided ”as is”, without warranty of any kind, express or implied, including But not limitedtothe warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authorsor copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, Arising from, out of or in connection with the software or the use or other dealings in the software.
    [Show full text]
  • An Exploration of the Effects of Enhanced Compiler Error Messages for Computer Programming Novices
    Technological University Dublin ARROW@TU Dublin Theses LTTC Programme Outputs 2015-11 An Exploration Of The Effects Of Enhanced Compiler Error Messages For Computer Programming Novices Brett A. Becker Technological University Dublin Follow this and additional works at: https://arrow.tudublin.ie/ltcdis Part of the Computer and Systems Architecture Commons, and the Educational Methods Commons Recommended Citation Becker, B. (2015) An exploration of the effects of enhanced compiler error messages for computer programming novices. Thesis submitted to Technologicl University Dublin in part fulfilment of the requirements for the award of Masters (M.A.) in Higher Education, November 2015. This Theses, Masters is brought to you for free and open access by the LTTC Programme Outputs at ARROW@TU Dublin. It has been accepted for inclusion in Theses by an authorized administrator of ARROW@TU Dublin. For more information, please contact [email protected], [email protected]. This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 4.0 License An Exploration of the Effects of Enhanced Compiler Error Messages for Computer Programming Novices A thesis submitted to Dublin Institute of Technology in part fulfilment of the requirements for the award of Masters (M.A.) in Higher Education by Brett A. Becker November 2015 Supervisor: Dr Claire McDonnell Learning Teaching and Technology Centre, Dublin Institute of Technology Declaration I certify that this thesis which I now submit for examination for the award of Masters (M.A.) in Higher Education is entirely my own work and has not been taken from the work of others, save and to the extent that such work has been cited and acknowledged within the text of my own work.
    [Show full text]
  • Directing Javascript with Arrows
    Directing JavaScript with Arrows Khoo Yit Phang Michael Hicks Jeffrey S. Foster Vibha Sazawal University of Maryland, College Park {khooyp,mwh,jfoster,vibha}@cs.umd.edu Abstract callback with a (short) timeout. Unfortunately, this style of event- JavaScript programmers make extensive use of event-driven pro- driven programming is tedious, error-prone, and hampers reuse. gramming to help build responsive web applications. However, The callback sequencing code is strewn throughout the program, standard approaches to sequencing events are messy, and often and very often each callback must hard-code the names of the next lead to code that is difficult to understand and maintain. We have events and callbacks in the chain. found that arrows, a generalization of monads, are an elegant solu- To combat this problem, many researchers and practitioners tion to this problem. Arrows allow us to easily write asynchronous have developed libraries to ease the construction of rich and highly programs in small, modular units of code, and flexibly compose interactive web applications. Examples include jQuery (jquery. them in many different ways, while nicely abstracting the details of com), Prototype (prototypejs.org), YUI (developer.yahoo. asynchronous program composition. In this paper, we present Ar- com/yui), MochiKit (mochikit.com), and Dojo (dojotoolkit. rowlets, a new JavaScript library that offers arrows to the everyday org). These libraries generally provide high-level APIs for com- JavaScript programmer. We show how to use Arrowlets to construct mon features, e.g., drag-and-drop, animation, and network resource a variety of state machines, including state machines that branch loading, as well as to handle API differences between browsers.
    [Show full text]
  • Applicative Programming with Effects
    Under consideration for publication in J. Functional Programming 1 FUNCTIONALPEARL Applicative programming with effects CONOR MCBRIDE University of Nottingham ROSS PATERSON City University, London Abstract In this paper, we introduce Applicative functors—an abstract characterisation of an ap- plicative style of effectful programming, weaker than Monads and hence more widespread. Indeed, it is the ubiquity of this programming pattern that drew us to the abstraction. We retrace our steps in this paper, introducing the applicative pattern by diverse exam- ples, then abstracting it to define the Applicative type class and introducing a bracket notation which interprets the normal application syntax in the idiom of an Applicative functor. Further, we develop the properties of applicative functors and the generic opera- tions they support. We close by identifying the categorical structure of applicative functors and examining their relationship both with Monads and with Arrows. 1 Introduction This is the story of a pattern that popped up time and again in our daily work, programming in Haskell (Peyton Jones, 2003), until the temptation to abstract it became irresistable. Let us illustrate with some examples. Sequencing commands One often wants to execute a sequence of commands and collect the sequence of their responses, and indeed there is such a function in the Haskell Prelude (here specialised to IO): sequence :: [IO a ] → IO [a ] sequence [ ] = return [] sequence (c : cs) = do x ← c xs ← sequence cs return (x : xs) In the (c : cs) case, we collect the values of some effectful computations, which we then use as the arguments to a pure function (:). We could avoid the need for names to wire these values through to their point of usage if we had a kind of ‘effectful application’.
    [Show full text]
  • The Glasgow Haskell Compiler User's Guide, Version 4.08
    The Glasgow Haskell Compiler User's Guide, Version 4.08 The GHC Team The Glasgow Haskell Compiler User's Guide, Version 4.08 by The GHC Team Table of Contents The Glasgow Haskell Compiler License ........................................................................................... 9 1. Introduction to GHC ....................................................................................................................10 1.1. The (batch) compilation system components.....................................................................10 1.2. What really happens when I “compile” a Haskell program? .............................................11 1.3. Meta-information: Web sites, mailing lists, etc. ................................................................11 1.4. GHC version numbering policy .........................................................................................12 1.5. Release notes for version 4.08 (July 2000) ........................................................................13 1.5.1. User-visible compiler changes...............................................................................13 1.5.2. User-visible library changes ..................................................................................14 1.5.3. Internal changes.....................................................................................................14 2. Installing from binary distributions............................................................................................16 2.1. Installing on Unix-a-likes...................................................................................................16
    [Show full text]
  • Learn You a Haskell for Great Good! © 2011 by Miran Lipovača 3 SYNTAX in FUNCTIONS 35 Pattern Matching
    C ONTENTSINDETAIL INTRODUCTION xv So, What’s Haskell? .............................................................. xv What You Need to Dive In ........................................................ xvii Acknowledgments ................................................................ xviii 1 STARTING OUT 1 Calling Functions ................................................................. 3 Baby’s First Functions ............................................................. 5 An Intro to Lists ................................................................... 7 Concatenation ........................................................... 8 Accessing List Elements ................................................... 9 Lists Inside Lists .......................................................... 9 Comparing Lists ......................................................... 9 More List Operations ..................................................... 10 Texas Ranges .................................................................... 13 I’m a List Comprehension.......................................................... 15 Tuples ........................................................................... 18 Using Tuples............................................................. 19 Using Pairs .............................................................. 20 Finding the Right Triangle ................................................. 21 2 BELIEVE THE TYPE 23 Explicit Type Declaration .......................................................... 24
    [Show full text]
  • SOME USEFUL STRUCTURES for CATEGORICAL APPROACH for PROGRAM BEHAVIOR in Computer Science, Where We Often Use More Complex Structures Not Expressible by Sets
    JIOS, VOL. 35, NO. 1 (2011) SUBMITTED 02/11; ACCEPTED 03/11 UDC 004.423.45 [ SomeSome useful Useful structures Structures for categorical for Categorical approach Approach for program for Programbehavior Behavior Viliam Slodicákˇ [email protected] Department of Computers and Informatics Faculty of Electrical Engineering and Informatics Technical university of Košice Letná 9, 042 00 Košice Slovak Republic Abstract Using of category theory in computer science has extremely grown in the last decade. Categories allow us to express mathematical structures in unified way. Algebras are used for constructing basic structures used in computer programs. A program can be considered as an element of the initial algebra arising from the used programming language. In our contribution we formulate two ways of expressing algebras in categories. We also construct the codomain functor from the arrow category of algebras into the base category of sets which objects are also the carrier-sets of the algebras. This functor expresses the relation between algebras and carrier-sets. Keywords: Algebra, arrow category, monad, Kleisli category, codomain functor 1. Introduction Knowing and proving of the expected behavior of complex program systems is very important and actual rôle. It carries the time and cost savings: in mathematics [8] or in practical applications of economical character. The aim of programming is to construct such correct programs and program systems that during their execution provide expected behavior [7]. A program can be considered as an element of the initial algebra arising from the used programming language [14]. Algebraic structures and number systems are widely used in computer science.
    [Show full text]
  • The Bluej Environment Reference Manual
    The BlueJ Environment Reference Manual Version 2.0 for BlueJ Version 2.0 Kasper Fisker Michael Kölling Mærsk Mc-Kinney Moller Institute University of Southern Denmark HOW DO I ... ? – INTRODUCTION ........................................................................................................ 1 ABOUT THIS DOCUMENT................................................................................................................................. 1 RELATED DOCUMENTS.................................................................................................................................... 1 REPORT AN ERROR.......................................................................................................................................... 1 USING THE CONTEXT MENU........................................................................................................................... 1 1 PROJECTS.......................................................................................................................................... 2 1.1 CREATE A NEW PROJECT................................................................................................................... 2 1.2 OPEN A PROJECT ............................................................................................................................... 2 1.3 FIND OUT WHAT A PROJECT DOES .................................................................................................... 2 1.4 COPY A PROJECT ..............................................................................................................................
    [Show full text]
  • There Is No Fork: an Abstraction for Efficient, Concurrent, and Concise Data Access
    There is no Fork: an Abstraction for Efficient, Concurrent, and Concise Data Access Simon Marlow Louis Brandy Jonathan Coens Jon Purdy Facebook Facebook Facebook Facebook [email protected] [email protected] [email protected] [email protected] Abstract concise business logic, uncluttered by performance-related details. We describe a new programming idiom for concurrency, based on In particular the programmer should not need to be concerned Applicative Functors, where concurrency is implicit in the Applica- with accessing external data efficiently. However, one particular tive <*> operator. The result is that concurrent programs can be problem often arises that creates a tension between conciseness and written in a natural applicative style, and they retain a high degree efficiency in this setting: accessing multiple remote data sources of clarity and modularity while executing with maximal concur- efficiently requires concurrency, and that normally requires the rency. This idiom is particularly useful for programming against programmer to intervene and program the concurrency explicitly. external data sources, where the application code is written without When the business logic is only concerned with reading data the use of explicit concurrency constructs, while the implementa- from external sources and not writing, the programmer doesn’t tion is able to batch together multiple requests for data from the care about the order in which data accesses happen, since there same source, and fetch data from multiple sources concurrently. are no side-effects that could make the result different when the Our abstraction uses a cache to ensure that multiple requests for order changes. So in this case the programmer would be entirely the same data return the same result, which frees the programmer happy with not having to specify either ordering or concurrency, from having to arrange to fetch data only once, which in turn leads and letting the system perform data access in the most efficient way to greater modularity.
    [Show full text]
  • An Introduction to Applicative Functors
    An Introduction to Applicative Functors Bocheng Zhou What Is an Applicative Functor? ● An Applicative functor is a Monoid in the category of endofunctors, what's the problem? ● WAT?! Functions in Haskell ● Functions in Haskell are first-order citizens ● Functions in Haskell are curried by default ○ f :: a -> b -> c is the curried form of g :: (a, b) -> c ○ f = curry g, g = uncurry f ● One type declaration, multiple interpretations ○ f :: a->b->c ○ f :: a->(b->c) ○ f :: (a->b)->c ○ Use parentheses when necessary: ■ >>= :: Monad m => m a -> (a -> m b) -> m b Functors ● A functor is a type of mapping between categories, which is applied in category theory. ● What the heck is category theory? Category Theory 101 ● A category is, in essence, a simple collection. It has three components: ○ A collection of objects ○ A collection of morphisms ○ A notion of composition of these morphisms ● Objects: X, Y, Z ● Morphisms: f :: X->Y, g :: Y->Z ● Composition: g . f :: X->Z Category Theory 101 ● Category laws: Functors Revisited ● Recall that a functor is a type of mapping between categories. ● Given categories C and D, a functor F :: C -> D ○ Maps any object A in C to F(A) in D ○ Maps morphisms f :: A -> B in C to F(f) :: F(A) -> F(B) in D Functors in Haskell class Functor f where fmap :: (a -> b) -> f a -> f b ● Recall that a functor maps morphisms f :: A -> B in C to F(f) :: F(A) -> F(B) in D ● morphisms ~ functions ● C ~ category of primitive data types like Integer, Char, etc.
    [Show full text]
  • Companion Object
    1. Functional Programming Functional Programming What is functional programming? What is it good for? Why to learn it? Functional Programming Programs as a composition of pure functions. Pure function? Deterministic. Same result for the same inputs. Produces no observable side eects. fun mergeAccounts(acc1: Account, acc2: Account): Account = Account(acc1.balance + acc2.balance) val mergedAcc = mergeAccounts(Account(500), Account(1000)) Target platform: JVM Running on Arrow v. 0.11.0-SNAPSHOT Running on Kotlin v. 1.3.50 Referential Transparency Function can be replaced with its corresponding value without changing the program's behavior. Based on the substitution model. Referential Transparency Better reasoning about program behavior. Pure functions referentially transparent. Substitution model Replace a named reference (function) by its value. Based on equational reasoning. Unlocks local reasoning. fun add(a: Int, b: Int): Int = a + b val two = add(1, 1) // could be replaced by 2 everywhere in the program val equal = (two == 1 + 1) Target platform: JVM Running on Arrow v. 0.11.0-SNAPSHOT Running on Kotlin v. 1.3.50 Substitution model Same example, but with two Accounts. fun mergeAccounts(acc1: Account, acc2: Account): Account = Account(acc1.balance + acc2.balance) val mergedAcc = mergeAccounts(Account(100), Account(200)) // could be replaced by Account(300) everywhere // in the program val equal = (mergedAcc == Account(300)) Target platform: JVM Running on Arrow v. 0.11.0-SNAPSHOT Running on Kotlin v. 1.3.50 Side eect? Function tries to access or modify the external world. val accountDB = AccountDB() fun mergeAccounts(acc1: Account, acc2: Account): Account { val merged = Account(acc1.balance + acc2.balance) accountDB.remove(listOf(acc1, acc2)) // side effect! accountDB.save(merged) // side effect! return merged } val merged = mergeAccounts(Account(100), Account(400)) Target platform: JVM Running on Arrow v.
    [Show full text]