More on functional programming

Similar documents
Programming in Haskell Aug Nov 2015

Background Type Classes (1B) Young Won Lim 6/14/18

Background Type Classes (1B) Young Won Lim 6/28/18

Monads. Bonus lecture 2017 David Sands

CS 440: Programming Languages and Translators, Spring 2019 Mon 2/4

Monad Background (3A) Young Won Lim 11/20/17

Background Operators (1E) Young Won Lim 7/7/18

Monads seen so far: IO vs Gen

Overview. Declarative Languages. General monads. The old IO monad. Sequencing operator example. Sequencing operator

Monad Background (3A) Young Won Lim 10/5/17

IO Monad (3D) Young Won Lim 1/18/18

Applicatives Comparisons (2C) Young Won Lim 3/6/18

Maybe Monad (3B) Young Won Lim 12/21/17

Haskell Monads CSC 131. Kim Bruce

I/O in Haskell. To output a character: putchar :: Char -> IO () e.g., putchar c. To output a string: putstr :: String -> IO () e.g.

References. Monadic I/O in Haskell. Digression, continued. Digression: Creating stand-alone Haskell Programs

Monad P1 : Several Monad Types (4A) Young Won Lim 2/13/19

Monad Background (3A) Young Won Lim 11/18/17

Monad class. Example: Lambda laughter. The functional IO problem. EDAN40: Functional Programming Functors and Monads

IO Monad (3C) Young Won Lim 1/6/18

Monad Background (3A) Young Won Lim 11/8/17

Using Monads for Input and Output

Monad (1A) Young Won Lim 6/9/17

Introduction to Haskell

Monad (3A) Young Won Lim 8/9/17

Maybe Monad (3B) Young Won Lim 1/3/18

Box-and-arrow Diagrams

Monad (1A) Young Won Lim 6/26/17

Programming Languages

Monad (1A) Young Won Lim 6/21/17

Haskell. COS 326 Andrew W. Appel Princeton University. a lazy, purely functional language. slides copyright David Walker and Andrew W.

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

Monads. Functional Programming (CS4011) Monads

Typed Racket: Racket with Static Types

I/O in Purely Functional Languages. Stream-Based I/O. Continuation-Based I/O. Monads

Standard prelude. Appendix A. A.1 Classes

Haskell Session Types with (Almost) No Class. Presented by Christian Harrington, Thomas Didriksen, Morten Fangel & Sune Alkærsig

Computer Science 1 Honors

Functional Programming

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

Programming Paradigms

Pointers, Dynamic Data, and Reference Types

Expressions and Variables

Advanced Programming Handout 7. Monads and Friends (SOE Chapter 18)

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules

Haskell & functional programming, some slightly more advanced stuff. Matteo Pradella

Software System Design and Implementation

Programming Paradigms and Languages Introduction to Haskell. dr Robert Kowalczyk WMiI UŁ

INTERACTION FUNCTIONS

COP4020 Programming Assignment 1 - Spring 2011

Solution sheet 1. Introduction. Exercise 1 - Types of values. Exercise 2 - Constructors

Introduction to Functional Programming and Haskell. Aden Seaman

CS 11 Haskell track: lecture 1

GHCi: Getting started (1A) Young Won Lim 5/31/17

1 Delimited continuations in Haskell

A Fast Review of C Essentials Part I

CS 11 Haskell track: lecture 4. n This week: Monads!

CS115 - Module 4 - Compound data: structures

CSC324 Principles of Programming Languages

Functional Programming and Haskell

Functional Programming in C++

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

Mostly functional programming does not work

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

The Typed Racket Guide

Monads in Haskell. Nathanael Schilling. December 12, 2014

CSCE 314 Programming Languages Functors, Applicatives, and Monads

Appendix B Boost.Python

CS115 - Module 9 - filter, map, and friends

Polymorphism Overview (1A) Young Won Lim 2/20/18

3.1. Chapter 3: The cin Object in Program 3-1. Displaying a Prompt 8/23/2014. The cin Object

Chapter 3: Expressions and Interactivity

GHCi: Getting started (1A) Young Won Lim 6/3/17

Lists, loops and decisions

Jython. secondary. memory

Parser Tools: lex and yacc-style Parsing

Haskell Refresher Informatics 2D

Programming Paradigms Written Exam (6 CPs)

Chapter 3: Expressions and Interactivity. Copyright 2012 Pearson Education, Inc. Thursday, October 9, 14

Types in Programming Languages Dynamic and Static Typing, Type Inference (CTM 2.8.3, EPL* 4) Abstract Data Types (CTM 3.7) Monads (GIH** 9)

Intro to Haskell Notes: Part 5

Part 0. A (Not So) Brief Introduction to Haskell

ITP 342 Mobile App Dev. Strings

Python I. Some material adapted from Upenn cmpe391 slides and other sources

HASKELL I/O. Curt Clifton Rose-Hulman Institute of Technology. Please SVN Update your HaskellInClass folder, then open eieio.hs

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

CS 457/557: Functional Languages

Client-Side Web Technologies. JavaScript Part I

Lazy Functional Programming in Haskell

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

Functional Programming

The Idris Tutorial. Release The Idris Community

Outline. 1 If Statement. 2 While Statement. 3 For Statement. 4 Nesting. 5 Applications. 6 Other Conditional and Loop Constructs 2 / 19

Decisions, Decisions. Testing, testing C H A P T E R 7

BLM2031 Structured Programming. Zeyneb KURT

Programming Systems in Artificial Intelligence Functional Programming

The Worker/Wrapper Transformation

CS 11 Haskell track: lecture 5. This week: State monads

Concepts of programming languages

Transcription:

More on functional programming Emphasis on Haskell (as a pure functional language) Input and output in Haskell Wrappers / contexts Monads chaining wrapped computations Maybe and lists as monads Return of I/O as a monad Error handling with Either monad

I/O in Haskell as actions Haskell is a pure functional language: functions cannot have side effects So, functions cannot do I/O! But functions can return actions, which can have side effects when they are run For functions, actions are just values (you cannot run them in a function) Bigger actions can be built by chaining actions together

main = do s <- getline f s f x = putstrln ( Hello ++ x ) The Tale of Two Worlds

I/O in Haskell as actions When a Haskell program is run function main is called main returns an action the action is executed the action may evaluate other functions (which return values but have no side effects) the functions/actions may return further actions Bingo: functions are still functional, actions can do I/O

Haskell I/O actions Haskell has functions (and actions) returning basic I/O actions getline :: IO String returns an action from which a string can be extracted putstrln :: String -> IO ( ) takes a string and returns an action which prints the string + line break, no value can be extracted out and more (read from file, network, GUI, )

Chaining actions (do-block) do-notation builds new actions by chaining actions together in sequence Values can be extracted from actions to new variables greet str = do putstrln ( Greetings, ++ str ) main = do putstrln Give your name name <- getline greet name

Chaining actions (do-block) Return clause can be used in actions to produce value that can be extracted askint :: String -> IO Int askint msg = do putstrln msg str <- getline return ( read str ) read :: (Read a) => String -> a show :: (Show a) => a -> String main = do num <- askint Give a number let twice = 2 * num in putstrln ( ( show num ) ++ twice is ++ ( show twice ) )

Return of Maybe Short reminder: Values of type Maybe Int either contain an integer or nothing Just 5: a maybe value that contains 5 Nothing: a maybe value that contains nothing A maybe value is not an integer, but it (maybe) contains / wraps an integer

Using Maybe types Maybe Int is good for error handling (Nothing = error): mysqrt x x >= 0 = Just ( sqrt x ) otherwise = Nothing How to mix Int and Maybe Int? mysqrt ( mysqrt 4 ) -- Error! What we need are monads

Wrappers / contexts A value (of type X) is wrapped inside a value of another type vector<int>, struct, or double* in C++ Maybe in Haskell (Nothing or Just 5) Lists in Haskell ( [ ], [ 3, 5 ], [ 10.. ] ) Lots of others as well

Monads A monad has an operation which takes a wrapped value & a function unwraps the value gives it to the function returns the (wrapped) return value of the function The operation is written >>= (and called bind) (Monads have other operations as well)

Maybe & lists as monads Maybe is defined as a monad! Just 4 >>= mysqrt -- Just 2.0 Just (-1) >>= mysqrt -- Nothing Nothing >>= mysqrt -- Nothing Lists as monads, >>= feeds elements to function and concatenates resulting lists mysqrts x x >= 0 = [ sqrt x, -sqrt x ] otherwise = [ ] [ 4, -1, 9 ] >>= mysqrt -- [ 2, -2, 3, -3 ]

Monads and I/O I/O actions from which a value can be extracted (IO Int, IO String, ) are wrappers They are also monads The I/O do-blocks are exactly the same as the Maybe / list do-blocks

Chaining operations with monads Combining two square root calls mysqsq x = x >>= mysqrt >>= mysqrt What if we want: The do-notation is just syntactic sugar for monad operations! -- Ok foo x = 2 * ( mysqrt x ) + 1 -- Error! foo x = x >>= mysqrt >>= ( \a -> Just ( 2 * a + 1 ) ) foo2 x = do a <- mysqrt x return ( 2 * a + 1 ) foo2 4 -- Just 5.0 foo2 (-2) -- Nothing

Even better errors: Either Either types are like unions in C++, they contain either value of one type or of another Right creates a normal value, Left creates an error value mysqrte :: Float -> Either String Float mysqrte x x >= 0 = Right ( sqrt x ) otherwise = Left sqrt < 0 Either is a monad, foo works! foo3 4 -- Right 5 foo3 (-2) -- Left sqrt < 0 foo3 x = do a <- mysqrte x return ( 2 * a + 1 )