Haskell Language

Total Page:16

File Type:pdf, Size:1020Kb

Haskell Language Haskell Language #haskell Table of Contents About 1 Chapter 1: Getting started with Haskell Language 2 Remarks 2 Features: 2 Versions 2 Examples 3 Hello, World! 3 Explanation: 4 Factorial 5 Variation 1 5 Variation 2 5 Fibonacci, Using Lazy Evaluation 6 Getting started 7 Online REPL 7 GHC(i) 7 More advanced tools 9 Primes 9 Below 100 9 Unlimited 10 Traditional 10 Optimal trial division 10 Transitional 10 The Shortest Code 10 Declaring Values 10 Chapter 2: Applicative Functor 12 Introduction 12 Remarks 12 Definition 12 Examples 12 Alternative definition 12 Common instances of Applicative 13 Maybe 13 Lists 13 Infinite streams and zip-lists 13 Functions 14 Chapter 3: Arbitrary-rank polymorphism with RankNTypes 16 Introduction 16 Syntax 16 Examples 16 RankNTypes 16 Chapter 4: Arithmetic 17 Introduction 17 Remarks 17 The numeric typeclass hierarchy 17 Examples 19 Basic examples 19 `Could not deduce (Fractional Int) ...` 19 Function examples 20 Chapter 5: Arrows 21 Examples 21 Function compositions with multiple channels 21 Chapter 6: Attoparsec 23 Introduction 23 Parameters 23 Examples 23 Combinators 23 Bitmap - Parsing Binary Data 24 Chapter 7: Bifunctor 26 Syntax 26 Remarks 26 Examples 26 Common instances of Bifunctor 26 Two-element tuples 26 Either 26 first and second 27 Definition of Bifunctor 27 Chapter 8: Cabal 28 Syntax 28 Examples 29 Install packages 29 Working with sandboxes 29 Chapter 9: Category Theory 31 Examples 31 Category theory as a system for organizing abstraction 31 An example 31 A hint of Category Theory 31 Definition of a Category 32 Haskell types as a category 33 Definition of the category 33 Isomorphisms 33 Functors 33 Monads 34 Product of types in Hask 34 Categorical products 34 Products in Hask 35 Uniqueness up to isomorphism 35 Uniqueness of the decomposition 36 Coproduct of types in Hask 36 Intuition 36 Categorical coproducts 36 Coproducts in Hask 36 Haskell Applicative in terms of Category Theory 37 Chapter 10: Common functors as the base of cofree comonads 38 Examples 38 Cofree Empty ~~ Empty 38 Cofree (Const c) ~~ Writer c 38 Cofree Identity ~~ Stream 38 Cofree Maybe ~~ NonEmpty 39 Cofree (Writer w) ~~ WriterT w Stream 39 Cofree (Either e) ~~ NonEmptyT (Writer e) 39 Cofree (Reader x) ~~ Moore x 40 Chapter 11: Common GHC Language Extensions 41 Remarks 41 Examples 41 MultiParamTypeClasses 41 FlexibleInstances 41 OverloadedStrings 42 TupleSections 42 N-tuples 42 Mapping 43 UnicodeSyntax 43 BinaryLiterals 44 ExistentialQuantification 44 LambdaCase 45 RankNTypes 46 OverloadedLists 47 FunctionalDependencies 47 GADTs 48 ScopedTypeVariables 49 PatternSynonyms 49 RecordWildCards 50 Chapter 12: Common monads as free monads 51 Examples 51 Free Empty ~~ Identity 51 Free Identity ~~ (Nat,) ~~ Writer Nat 51 Free Maybe ~~ MaybeT (Writer Nat) 52 Free (Writer w) ~~ Writer [w] 52 Free (Const c) ~~ Either c 52 Free (Reader x) ~~ Reader (Stream x) 53 Chapter 13: Concurrency 54 Remarks 54 Examples 54 Spawning Threads with `forkIO` 54 Communicating between Threads with `MVar` 54 Atomic Blocks with Software Transactional Memory 55 atomically :: STM a -> IO a 56 readTVar :: TVar a -> STM a 56 writeTVar :: TVar a -> a -> STM () 56 Chapter 14: Containers - Data.Map 57 Examples 57 Constructing 57 Checking If Empty 57 Finding Values 57 Inserting Elements 58 Deleting Elements 58 Importing the Module 58 Monoid instance 58 Chapter 15: Creating Custom Data Types 60 Examples 60 Creating a simple data type 60 Creating variables of our custom type 60 Creating a data type with value constructor parameters 60 Creating variables of our custom type 61 Creating a data type with type parameters 61 Creating variables of our custom type 61 Custom data type with record parameters 61 Chapter 16: Data.Aeson - JSON in Haskell 63 Examples 63 Smart Encoding and Decoding using Generics 63 A quick way to generate a Data.Aeson.Value 64 Optional Fields 64 Chapter 17: Data.Text 65 Remarks 65 Examples 65 Text Literals 65 Stripping whitespace 65 Splitting Text Values 66 Encoding and Decoding Text 66 Checking if a Text is a substring of another Text 67 Indexing Text 67 Chapter 18: Databases 69 Examples 69 Postgres 69 Parameter substitution 69 Executing inserts or updates 69 Chapter 19: Date and Time 70 Syntax 70 Remarks 70 Examples 70 Finding Today's Date 70 Adding, Subtracting and Comparing Days 70 Chapter 20: Fixity declarations 72 Syntax 72 Parameters 72 Remarks 72 Examples 73 Associativity 73 Binding precedence 73 Remarks 73 Example declarations 74 Chapter 21: Foldable 75 Introduction 75 Remarks 75 Examples 75 Counting the elements of a Foldable structure 75 Folding a structure in reverse 75 An instance of Foldable for a binary tree 76 Flattening a Foldable structure into a list 77 Performing a side-effect for each element of a Foldable structure 77 Flattening a Foldable structure into a Monoid 78 Definition of Foldable 79 Checking if a Foldable structure is empty 79 Chapter 22: Foreign Function Interface 80 Syntax 80 Remarks 80 Examples 80 Calling C from Haskell 80 Passing Haskell functions as callbacks to C code. 81 Chapter 23: Free Monads 83 Examples 83 Free monads split monadic computations into data structures and interpreters 83 Free Monads are like fixed points 84 How do foldFree and iterM work? 84 The Freer monad 85 Chapter 24: Function call syntax 87 Introduction 87 Remarks 87 Examples 87 Parentheses in a basic function call 87 Parentheses in embedded function calls 87 Partial application - Part 1 88 Partial application - Part 2 88 Chapter 25: Function composition 90 Remarks 90 Examples 91 Right-to-left composition 91 Left-to-right composition 91 Composition with binary function 91 Chapter 26: Functor 93 Introduction 93 Remarks 93 Identity 93 Composition 93 Examples 93 Common instances of Functor 93 Maybe 93 Lists 94 Functions 95 Class Definition of Functor and Laws 95 Replacing all elements of a Functor with a single value 96 Polynomial functors 96 The identity functor 96 The constant functor 97 Functor products 97 Functor coproducts 97 Functor composition 98 Polynomial functors for generic programming 98 Functors in Category Theory 99 Deriving Functor 100 Chapter 27: Generalized Algebraic Data Types 101 Examples 101 Basic Usage 101 Chapter 28: GHCJS 102 Introduction 102 Examples 102 Running "Hello World!" with Node.js 102 Chapter 29: Google Protocol Buffers 103 Remarks 103 Examples 103 Creating, building and using a simple .proto file 103 Chapter 30: Graphics with Gloss 105 Examples 105 Installing Gloss 105 Getting something on the screen 105 Chapter 31: Gtk3 107 Syntax 107 Remarks 107 Examples 107 Hello World in Gtk 107 Chapter 32: Higher-order functions 109 Remarks 109 Examples 109 Basics of Higher Order Functions 109 Lambda Expressions 110 Currying 110 Chapter 33: Infix operators 112 Remarks 112 Examples 112 Prelude 112 Logical 112 Arithmetic operators 112 Lists 112 Control flow 113 Custom operators 113 Finding information about infix operators 114 Chapter 34: IO 115 Examples 115 Reading all contents of standard input into a string 115 Reading a line from standard input 115 Parsing and constructing an object from standard input 115 Reading from file handles 116 Checking for end-of-file conditions 117 Reading words from an entire file 117 IO defines your program's `main` action 118 Role and Purpose of IO 119 Manipulating IO values 119 IO semantics 120 Lazy IO 121 IO and do notation 121 Getting the 'a' "out of" 'IO a' 122 Writing to stdout 122 putChar :: Char -> IO () - writes a char to stdout 122 putStr :: String -> IO () - writes a String to stdout 122 putStrLn :: String -> IO () - writes a String to stdout and adds a new line 122 print :: Show a => a -> IO () - writes a an instance of Show to stdout 123 Reading from `stdin` 123 getChar :: IO Char - read a Char from stdin 123 getLine :: IO String - read a String from stdin, sans new line character 123 read :: Read a => String -> a - convert a String to a value 124 Chapter 35: Lens 125 Introduction 125 Remarks 125 What is a Lens? 125 Focusing 125 Other Optics 125 Composition 126 In Haskell 126 Examples 126 Manipulating tuples with Lens 126 Lenses for records 127 Simple record 127 Managing records with repeating fields names 127 Stateful Lenses 128 Getting rid of & chains 128 Imperative code with structured state 128 Writing a lens without Template Haskell 129 Lens and Prism 129 Traversals 130 Lenses compose 130 Classy Lenses 131 Fields with makeFields 131 Chapter 36: List Comprehensions 134 Examples 134 Basic List Comprehensions 134 Patterns in Generator Expressions 134 Guards 135 Nested Generators 135 Parallel Comprehensions 135 Local Bindings 136 Do Notation 136 Chapter 37: Lists 137 Syntax 137 Remarks 137 Examples 138 List Literals 138 List Concatenation 138 List basics 138 Processing lists 139 Accessing elements in lists 139 Ranges 140 Basic Functions on Lists 141 foldl 141 foldr 142 Transforming with `map` 142 Filtering with `filter` 143 Zipping and Unzipping Lists 143 Chapter 38: Logging 145 Introduction 145 Examples 145 Logging with hslogger 145 Chapter 39: Modules 146 Syntax 146 Remarks 146 Examples 146 Defining Your Own Module 146 Exporting Constructors 147 Importing Specific Members of a Module 147 Hiding Imports 147 Qualifying Imports 148 Hierarchical module names 148 Chapter 40: Monad Transformers 149 Examples 149 A monadic counter 149 Adding an environment 149 The requirements changed: we need logging! 150 Doing everything in one go 151 Chapter 41: Monads 153 Introduction 153 Examples 153 The Maybe monad 153 IO monad 155 List Monad 156 Monad as a Subclass of Applicative
Recommended publications
  • 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]
  • 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]
  • 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]
  • 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]
  • 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
    [Show full text]
  • Cofree Traversable Functors
    IT 19 035 Examensarbete 15 hp September 2019 Cofree Traversable Functors Love Waern Institutionen för informationsteknologi Department of Information Technology Abstract Cofree Traversable Functors Love Waern Teknisk- naturvetenskaplig fakultet UTH-enheten Traversable functors see widespread use in purely functional programming as an approach to the iterator pattern. Unlike other commonly used functor families, free Besöksadress: constructions of traversable functors have not yet been described. Free constructions Ångströmlaboratoriet Lägerhyddsvägen 1 have previously found powerful applications in purely functional programming, as they Hus 4, Plan 0 embody the concept of providing the minimal amount of structure needed to create members of a complex family out of members of a simpler, underlying family. This Postadress: thesis introduces Cofree Traversable Functors, together with a provably valid Box 536 751 21 Uppsala implementation, thereby developing a family of free constructions for traversable functors. As free constructions, cofree traversable functors may be used in order to Telefon: create novel traversable functors from regular functors. Cofree traversable functors 018 – 471 30 03 may also be leveraged in order to manipulate traversable functors generically. Telefax: 018 – 471 30 00 Hemsida: http://www.teknat.uu.se/student Handledare: Justin Pearson Ämnesgranskare: Tjark Weber Examinator: Johannes Borgström IT 19 035 Tryckt av: Reprocentralen ITC Contents 1 Introduction7 2 Background9 2.1 Parametric Polymorphism and Kinds..............9 2.2 Type Classes........................... 11 2.3 Functors and Natural Transformations............. 12 2.4 Applicative Functors....................... 15 2.5 Traversable Functors....................... 17 2.6 Traversable Morphisms...................... 22 2.7 Free Constructions........................ 25 3 Method 27 4 Category-Theoretical Definition 28 4.1 Applicative Functors and Applicative Morphisms......
    [Show full text]
  • Notions of Computation As Monoids 3
    ZU064-05-FPR main 19 June 2014 0:23 Under consideration for publication in J. Functional Programming 1 Notions of Computation as Monoids EXEQUIEL RIVAS MAURO JASKELIOFF Centro Internacional Franco Argentino de Ciencias de la Informaci´on y de Sistemas CONICET, Argentina FCEIA, UniversidadNacionalde Rosario, Argentina Abstract There are different notions of computation, the most popular being monads, applicative functors, and arrows. In this article we show that these three notions can be seen as monoids in a monoidal category. We demonstrate that at this level of abstraction one can obtain useful results which can be instantiated to the different notions of computation. In particular, we show how free constructions and Cayley representations for monoids translate into useful constructions for monads, applicative functors, and arrows. Moreover, the uniform presentation of all three notions helps in the analysis of the relation between them. 1 Introduction When constructing a semantic model of a system or when structuring computer code, there are several notions of computation that one might consider. Monads (Moggi, 1989; Moggi, 1991) are the most popular notion, but other notions, such as arrows (Hughes, 2000) and, more recently, applicative functors (McBride & Paterson, 2008) have been gaining widespread acceptance. Each of these notions of computation has particular characteristics that makes them more suitable for some tasks than for others. Nevertheless, there is much to be gained from arXiv:1406.4823v1 [cs.LO] 29 May 2014 unifying all three different notions under a single conceptual framework. In this article we show how all three of these notions of computation can be cast as a monoid in a monoidal category.
    [Show full text]
  • Applicative Programming with Effects
    City Research Online City, University of London Institutional Repository Citation: Mcbride, C. and Paterson, R. A. (2008). Applicative programming with effects. Journal of Functional Programming, 18(1), pp. 1-13. doi: 10.1017/S0956796807006326 This is the draft version of the paper. This version of the publication may differ from the final published version. Permanent repository link: https://openaccess.city.ac.uk/id/eprint/13222/ Link to published version: http://dx.doi.org/10.1017/S0956796807006326 Copyright: City Research Online aims to make research outputs of City, University of London available to a wider audience. Copyright and Moral Rights remain with the author(s) and/or copyright holders. URLs from City Research Online may be freely distributed and linked to. Reuse: Copies of full items can be used for personal research or study, educational, or not-for-profit purposes without prior permission or charge. Provided that the authors, title and full bibliographic details are credited, a hyperlink and/or URL is given for the original metadata page and the content is not changed in any way. City Research Online: http://openaccess.city.ac.uk/ [email protected] 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.
    [Show full text]
  • UNIVERSITY of CALIFORNIA SAN DIEGO Front-End Tooling For
    UNIVERSITY OF CALIFORNIA SAN DIEGO Front-end tooling for building and maintaining dependently-typed functional programs A dissertation submitted in partial satisfaction of the requirements for the degree of Doctor of Philosophy in Computer Science by Valentin Robert Committee in charge: Professor Sorin Lerner, Chair Professor William Griswold Professor James Hollan Professor Ranjit Jhala Professor Todd Millstein 2018 Copyright Valentin Robert, 2018 All rights reserved. The Dissertation of Valentin Robert is approved and is acceptable in qual- ity and form for publication on microfilm and electronically: Chair University of California San Diego 2018 iii TABLE OF CONTENTS Signature Page .............................................................. iii Table of Contents ........................................................... iv List of Figures .............................................................. vi List of Tables ............................................................... viii Acknowledgements ......................................................... ix Vita ........................................................................ xii Abstract of the Dissertation .................................................. xiii Introduction ................................................................ 1 Chapter 1 Background .................................................... 5 1.1 Static typing ........................................................ 5 1.2 Dependent types ................................................... 7
    [Show full text]
  • Selective Applicative Functors
    Selective Applicative Functors ANDREY MOKHOV, Newcastle University, United Kingdom GEORGY LUKYANOV, Newcastle University, United Kingdom SIMON MARLOW, Facebook, United Kingdom 90 JEREMIE DIMINO, Jane Street, United Kingdom Applicative functors and monads have conquered the world of functional programming by providing general and powerful ways of describing effectful computations using pure functions. Applicative functors provide a way to compose independent effects that cannot depend on values produced by earlier computations, and all of which are declared statically. Monads extend the applicative interface by making it possible to compose dependent effects, where the value computed by one effect determines all subsequent effects, dynamically. This paper introduces an intermediate abstraction called selective applicative functors that requires all effects to be declared statically, but provides a way to select which of the effects to execute dynamically. We demonstrate applications of the new abstraction on several examples, including two industrial case studies. CCS Concepts: · Software and its engineering;· Mathematics of computing; Additional Key Words and Phrases: applicative functors, selective functors, monads, effects ACM Reference Format: Andrey Mokhov, Georgy Lukyanov, Simon Marlow, and Jeremie Dimino. 2019. Selective Applicative Functors. Proc. ACM Program. Lang. 3, ICFP, Article 90 (August 2019), 29 pages. https://doi.org/10.1145/3341694 1 INTRODUCTION Monads, introduced to functional programming by Wadler [1995], are a powerful and general approach for describing effectful (or impure) computations using pure functions. The key ingredient of the monad abstraction is the bind operator, denoted by >>= in Haskell1: (>>=) :: Monad f => f a -> (a -> f b) -> f b The operator takes two arguments: an effectful computation f a, which yields a value of type a when executed, and a recipe, i.e.
    [Show full text]
  • A Layered Formal Framework for Modeling of Cyber-Physical Systems
    1 A Layered Formal Framework for Modeling of Cyber-Physical Systems George Ungureanu and Ingo Sander School of Information and Communication Technology KTH Royal Institute of Technology Stockholm, Sweden Email: ugeorge, ingo @kth.se f g Abstract Designing cyber-physical systems is highly challenging due to its manifold interdependent aspects such as composition, timing, synchronization and behavior. Several formal models exist for description and analysis of these aspects, but they focus mainly on a single or only a few system properties. We propose a formal composable frame- work which tackles these concerns in isolation, while capturing interaction between them as a single layered model. This yields a holistic, fine-grained, hierarchical and structured view of a cyber-physical system. We demonstrate the various benefits for modeling, analysis and synthesis through a typical example. I. INTRODUCTION The orthogonalization of concerns, i.e. the separation of the various aspects of design, as already pointed out in 2000 by Keutzer et al. [1], is an essential component in a system design paradigm that allows a more effective exploration of alternative solutions. This paper aims at pushing this concept to its limits, by not only literally separating concerns and describing simple rules of interaction, but also deconstructing them to their most basic, composable semantics. We present a pure functional framework for describing, analyzing and simulating cyber-physical systems (CPS) as networks of processes communicating through signals similar to [2]–[8]. The purity inherent from describing behavior as side-effect free functions ensures that each and every entity is independent and contains self-sufficient semantics, enabling both the modeling and the simulation of true concurrency without the need of a global state or controller.
    [Show full text]