Functional Programming

Slides:



Advertisements
Similar presentations
CMSC 330: Organization of Programming Languages Tuples, Types, Conditionals and Recursion or “How many different OCaml topics can we cover in a single.
Advertisements

0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
0 PROGRAMMING IN HASKELL Typeclasses and higher order functions Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and.
Tuples and Lists Lecture 3, Programmeringsteknik del A.
September 19, 2012Introduction to Artificial Intelligence Lecture 5: Functional Programming with Haskell 1 Functional Programming Symbolic AI is based.
Haskell. 2 GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
11/1/20151 GC16/3011 Functional Programming Lecture 5 Miranda patterns, functions, recursion and lists.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Haskell Basics CSCE 314 Spring CSCE 314 – Programming Studio Using GHC and GHCi Log in to unix.cse.tamu.edu (or some other server) From a shell.
0 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Odds and Ends,
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
Haskell. GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
1 PROGRAMMING IN HASKELL Lecture 2 Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
1 PROGRAMMING IN HASKELL An Introduction Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
0 PROGRAMMING IN HASKELL Typeclasses and higher order functions Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and.
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
Functional Programming Lecture 1 - Introduction Professor Muffy Calder.
© M. Winter COSC 4P41 – Functional Programming Some functions id :: a -> a id x = x const :: a -> b -> a const k _ = k ($) :: (a -> b) -> a -> b.
Functional Programming
CS314 – Section 5 Recitation 9
Polymorphic Functions
Functional Programming
Chapter 4 Stacks
Functional Programming
Haskell: Syntax in Functions
Conditional Expressions
Recursion.
Midterm recap Total was 80 points Distribution range
Principles of programming languages 12: Functional programming
dr Robert Kowalczyk WMiI UŁ
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
Theory of Computation Lecture 4: Programs and Computable Functions II
Functional Programming Lecture 12 - more higher order functions
PROGRAMMING IN HASKELL
Functions and patterns
A lightening tour in 45 minutes
PROGRAMMING IN HASKELL
Functional Programming
Haskell.
CSE 3302 Programming Languages
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Higher Order Functions
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
Pattern Matching Pattern matching allows us to do things like this:
Artificial Intelligence Lecture 2: The Haskell Programming Language
Haskell Types, Classes, and Functions, Currying, and Polymorphism
PROGRAMMING IN HASKELL
Fundamentals of Functional Programming
HIGHER ORDER FUNCTIONS
CSE 3302 Programming Languages
Functions and patterns
CSCE 314: Programming Languages Dr. Dylan Shell
PROGRAMMING IN HASKELL
Functions and patterns
PROGRAMMING IN HASKELL
Functional Programming and Haskell
Theory of Computation Lecture 4: Programs and Computable Functions II
CISC101 Reminders Assignment 3 due today.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Functional Programming and Haskell
Presentation transcript:

Functional Programming The most striking feature of purely functional programming is that there is no state. This means that our variables are not variable, i.e., cannot change their values! In other words, they are immutable and only represent some constant value. The execution of a program only involves the evaluation of functions. This sounds weird – what are the advantages and disadvantages of functional programming? February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Functional Programming The advantage of having no state is that functions have no side effects. Therefore, we can be sure that whenever we evaluate a function with the same inputs, we will get the same output, and nothing in our system changed due to this evaluation. This prevents most of the bugs that commonly occur in imperative programming. It also allows for automatic multithreading. You will learn about other advantages when you study Haskell more closely. February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Functional Programming The main problem with strictly preventing side effects is that user input and output during program execution become impossible. To enable such user interaction, we have to sometimes allow state changes. It is then important to separate such “impure” code from the rest of the program. There are many functional languages, with some being as old as the earliest imperative ones. Examples are: LISP, Scheme, Haskell, Erlang, R, Clojure, Scala, OCaml, and F#. February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Functional Programming Functional programming is not the best solution to every problem, just like object-oriented programming is not, either. In the context of theory of computation, you will see how functional programming allows you easily translate mathematical definitions into concise and clear programs. Even if you rarely or never use Haskell again afterwards, it will give you a different perspective on programming and may change the way you program. February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Download the Haskell Platform at: https://www.haskell.org/ There are no perfect Haskell IDEs, but some good plugins for editors such as Atom, Sublime Text, or IntelliJ. For our purposes, a simple text editor plus console a good enough. For Windows, Notepad++ with the NppExec plugin gives you syntax highlighting and integrated coding, testing, and profiling. February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Example scripts for Notepad++: Compiling: ghc -O -o main.exe $(FULL_CURRENT_PATH) cmd /C main.exe Interactive testing/debugging: ghci $(FULL_CURRENT_PATH) Profiling: ghc -O -prof -auto-all $(FULL_CURRENT_PATH) $(NAME_PART) +RTS -p –RTS cmd /C more $(NAME_PART).prof February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Free Haskell tutorials: http://learnyouahaskell.com/ http://book.realworldhaskell.org/ I recommend that you read Chapters 1 and 2 of “Learn you a Haskell” and experiment with the language a bit. As I said before, it is not mandatory for you to learn Haskell, and it will not be relevant to homework or exams. It is just an opportunity that I am offering to you. February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Demo Session (I) Here is the protocol of our demo session with GHCi: *Main> 3 + 4 7 *Main> 2^1000 10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376 *Main> "hello" "hello" February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Demo Session (II) *Main> :t "hello" "hello" :: [Char] *Main> :t 3 3 :: Num a => a *Main> :t 3.5 3.5 :: Fractional a => a *Main> [3, 2, 1] [3,2,1] *Main> 4:[3, 2, 1] [4,3,2,1] *Main> 4:3:5:[] [4,3,5] February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Demo Session (III) *Main> (2, 3) (2,3) *Main> (2, 3) == (3, 2) False *Main> [2, 3] == [3, 2] *Main> (5, 'a') (5,'a') *Main> :t head head :: [a] -> a *Main> head [4, 6, 1] 4 February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Demo Session (IV) *Main> :t tail tail :: [a] -> [a] *Main> tail [4, 6, 1] [6,1] *Main> let mult a b = a*b *Main> mult 6 7 42 *Main> :t mult mult :: Num a => a -> a -> a *Main> head "hello" 'h' February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Demo Session (V) *Main> (mult 6) 8 48 *Main> let supermult = mult 6 *Main> supermult 5 30 *Main> :t supermult supermult :: Num a => a -> a *Main> even 7 False *Main> :t filter filter :: (a -> Bool) -> [a] -> [a] February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Demo Session (VI) *Main> :t even even :: Integral a => a -> Bool *Main> [1..10] [1,2,3,4,5,6,7,8,9,10] *Main> filter even [1..10] [2,4,6,8,10] *Main> :t map map :: (a -> b) -> [a] -> [b] *Main> map even [1..10] [False,True,False,True,False,True,False,True,False,True] February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Demo Session (VII) *Main> map supermult [1..10] [6,12,18,24,30,36,42,48,54,60] *Main> :{ *Main| fc 0 = 1 *Main| fc n = n*fc (n - 1) *Main| :} *Main> fc 3 6 *Main> fc 10 3628800 *Main> fc 30 265252859812191058636308480000000 February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Demo Session (VIII) *Main> [1..10] [1,2,3,4,5,6,7,8,9,10] *Main> head [1..10] 1 *Main> head [1..100000000000000000000000000000000] *Main> head [1..] Bottom line: Haskell is lazy! February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Function Application In Haskell, function application has precedence over all other operations. Since the compiler knows how many arguments each function requires, we can do the following: func1 x = x + 2 func2 x y = x*x + y*y func3 a b = func1 a + func2 b a No parentheses are necessary – the known signatures of func1 and func2 define how to compute func3. February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language If – Then - Else Remember that execution of purely functional Haskell code involves only function evaluation, and nothing else. Therefore, there is an if – then – else function, but it always has to return something, so we always need the “else” part. Furthermore, it needs to have a well-defined signature, which means that the expressions following “then” and “else” have to be of the same type. February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language If – Then - Else Example: iq :: Int -> [Char] iq n = if n > 130 then "Wow!" else "Bah!" You can put everything in a single line if you like, as in this example: max’ :: Int -> Int -> Int max’ x y = if x > y then x else y February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Some Functions on Lists head xs: Returns the first element of list xs tail xs: Returns list xs with its first element removed length xs: Returns the number of elements in list xs reverse xs: returns a list with the elements of xs in reverse order null xs: returns true if xs is an empty list and false otherwise February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Some Functions on Tuples fst p: Returns the first element of pair p snd p: Returns the second element of pair p This only works for pairs, but you can define your own functions for larger tuples, e.g.: fst3 :: (a, b, c) -> a fst3 (x, y, z) = x You can always replace variables whose values you do not need with an underscore: fst3(x, _, _) = x February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Some Functions on Tuples The Cartesian product is a good example of how to build lists of tuples using list comprehensions: cart xs ys = [(x, y) | x <- xs, y <- ys] > cart [1, 2], [‘a’, ‘b’, ‘c’] > [(1,‘a’),(1,‘b’),(1,‘c’),(2,‘a’),(2,‘b’), (2,‘c’)] Note that the assignment y <- ys first goes through all elements of ys before the value of x changes for the first time. The changes are “fastest” for the rightmost assignment and propagate to the left, like the digits of a decimal number when we count, e.g., from 100 to 999. February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Pattern Matching You can define separate output expressions for distinct patterns in the input to a function. This is also the best way to implement recursion, as in the factorial function: fact 0 = 1 fact n = n*fact (n – 1) Similarly, we can define recursion on a list, for example, to compute the sum of all its elements: sum’ [] = 0 sum’ (x:xs) = x + sum’ xs February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Pattern Matching We can even do things like this: testList [] = "empty" testList (x:[]) = "single-element" testList (x:xs) = "multiple elements. First one is " ++ show x The last line demonstrates how we can use pattern matching to not only specify a pattern but also access the relevant input elements in the function expression. Since we do not use xs in that line, we could as well write testList (x:_) = "multiple elements. First one is " ++ show x February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Guards In pattern matching, you have to specify exact patterns and values to distinguish different cases. If you need to check inequalities or call functions in order to make a match, you can use guards instead: iqGuards :: Int -> [Char] iqGuards n | n > 150 = “amazing!" | n > 100 = “cool!" | otherwise = "oh well..." February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Currying As you know, you can turn any infix operator into a prefix operator by putting it in parentheses: (+) 3 4 7 Now currying allows us to place the parentheses differently: (+ 3) 4 By “fixing” the first input to (+) to be 3, we created a new function (+ 3) that receives only one (further) input. February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Currying We can check this: :t (+ 3) (+ 3) :: Num a => a -> a This (+ 3) function can be used like any other function, for example: map (+ 3) [1..5] [4, 5, 6, 7, 8] Or: map (max 5) [1..10] [5, 5, 5, 5, 5, 6, 7, 8, 9, 10] February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Lambda Expressions Sometimes we just need a small local function that is not used anywhere else in the program. Then it is convenient to use a lambda expression, which is a way of defining an anonymous function directly in the place where we use it. They have the following form: \input -> output For example: (\x -> 3*x) 4 12 February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language

Theory of Computation Lecture 3: The Haskell Programming Language Lambda Expressions More examples for lambda expressions: zipWith (+) [1..10] [11..20] [12,14,16,18,20,22,24,26,28,30] zipWith (\x y -> x^2 + y^2) [1..10] [11..20] [122,148,178,212,250,292,338,388,442,500] map (\x -> (x, x^2, x^3)) [1..10] [(1, 1, 1),(2, 4, 8),(3, 9, 27),(4, 16, 64),(5, 25, 125)] February 5, 2019 Theory of Computation Lecture 3: The Haskell Programming Language