Functional Programming Charlie Li 6/4/2019 Content

Functional Programming Charlie Li 6/4/2019 Content

Functional Programming Charlie Li 6/4/2019 Content • Functional Programming • Haskell – Features • Haskell – Basic Types • Haskell – Classes • Haskell – Custom Types • Haskell – Infix Function • Haskell – Precedence and Associativity • Haskell – Partial Application Content • Haskell – Strict Type • Haskell – Syntax • Haskell – Pattern Matching • Haskell – Lists • Haskell – Folds • Haskell – Tuples • Haskell – Challenges • Haskell – More Functional Programing • Why functional programing? • Pros: • Less bug • Shorter and cleaner code • Focus on WHAT to calculate not HOW to calculate • Cons: • Looonger programming time and runtime • Compile errorsss Functional Programing • Pure function • A pure function is a function which gives the same result with the same input • No side effects • Outputting to screen is a side effect! Functional Programing • Which of the following functions are pure functions? void f1() { cout << "Hello World !" << endl; } int f2(int x) { return ++x; } int f3(int& x) { return ++x; } int f4(int x, int y) { return x + y; } Functional Programing • f1 is not a pure function! • It print the same string every time, isn’t it a constant function? • No, printing is a side effect, it changes your screen! • More precisely, it changes some part of the memory that does not belong to it Functional Programing • f2 is a pure function! • It has not side effects. • Although it changes the variable x, that x belongs to the function, not the outside world, so it is pure Functional Programing • f3 is not a pure function! • It has side effect. • Noted that x is passed by reference. • It changes the variable x which does not belong to itself Functional Programing • f4 is a pure function! • It has no side effects. • It returns the same output when the input is the same. Functional Programing • In a pure functional programing language, every function is a pure function • All variables are mathematically variables • It has Referential transparency, i.e. replacing the variable by its value does not change the behavior of the program • Global variables are essentially global constant • No input and output in the function • IO is troublesome and too difficult to be explained today Haskell - Features • Haskell is a pure functional programming language • Every function is a pure function • Haskell is statically typed • The type of variables are determined at compile time • Haskell supports type inference • The compile can detect the type of variables and functions even if it is not provided • Haskell supports lazy evaluation • The value of an expression is evaluated only if it is needed Haskell – Basic Types • Names of data types always starts with capital letter • Some basic types are: • Int • A 32-bit or 64-bit integer, depends on computer • Integer • Aka. Big integer • Double • Char • Bool • String Haskell – Basic Types • There are also two more kind of useful data types in Haskell • Lists • Every element are of the same type in a list (unlike Python) • There is no restriction on the length of lists • Yes, there are lists with infinite length • Tuples • Elements in a tuple may have different types • The largest tuple can have up to 62 entries Haskell – Basic Types • Lists • List are represented using brackets [] • [1, 2, 3] is a list of integer with length 3 • Its type maybe [Int] or [Double] or … • Tuples • Tuples are represented using parenthesis () • (1, ‘a’, [True, False]) is a tuple with three element • Its type maybe (Int, Char, [Bool]) or (Double, Char, [Bool]) or … Haskell Platform • Haskell Platform includes GHC (the Haskell compiler) and other useful tools • The latest version is 8.6.3, the installer for Windows can be downloaded here • You can find the download links for other OS at the bottom Haskell – Area • Let’s open ghci (winghci has better UI but cannot be used in this lab due to some permission issues) • Let’s first define a function to calculate the area of a rectangle • Type the following into ghci (let areaRect l w = l * w): • This is the definition of the function areaRect • What do you think will be the output of areaRect 2 3? Haskell – Area • Bingo • How about areaRect 2.5 3.5? Haskell – Area • Bingo • Next question, how about areaRect 2.5 3? Haskell – Area • Bingo • Next question, what do you think will be the type of areaRect? • Sometimes it takes two integers as input and return integer • Sometimes it takes two fractional numbers as input and return a fractional number Haskell – Area • In ghci, we can type :t name to check the type (aka. signature) of a function • The “::” tells that the following is the function type not a definition • The “Num a =>” part says that a is a type that belongs to the “Num” class • “Num” class contains all kinds of numbers, e.g. Int, Integer, Float, Double, … Haskell – Area • In ghci, we can type :t name to check the type (aka. signature) of a function • The “a -> a -> a” part is the type of the function • The last one is the type of the returned value • Others are the type of parameter • So area takes two parameter with the same type as input and return the same type • Also, this a must be some kind of number Haskell – Area • In ghci, we can type :t name to check the type (aka. signature) of a function • So this tells us that areaRect is a function that takes two numbers as input and return a number Haskell – Classes • Be careful, there is a bit difference between class and type • Haskell is a statically typed language • The existence of class is for safe function overload • There are similarity between class in Haskell and class in C++ • There are some inheritance relation • E.g. Integral a => Num a • But the class in Haskell is not the same as the class in C++ Haskell – Classes • There are many predefined classes in Haskell, the name are usually descriptive enough Haskell – Classes • Eq: All types that == and /= are defined • Ord: All types that <, >, <=, >= are defined • Num: All types of numbers • Real: All types of real numbers • Fractional: All types of numbers that are not necessarily integer • Integral: All types of integers • Foldable: All types that “foldr” is defined • Read: All types that “read” is defined • Show: All types that “show” is defined • … Haskell – Classes • So now do you know the type of [1, 2, 3] and (1, ‘a’, [True, False]) ? • How to check if you get the correct answer? • Just try to type :t [1, 2, 3] and :t (1, ‘a’, [True, False]) Haskell – Classes • Did you get it right? Haskell – Custom Type • In Haskell you can define your own type • Syntax like this: data Contact = Phone Integer | Email String data Maybe a = Just a | Nothing data Either a b = Left a | Right b data Ordering = LT | EQ | GT • Phone, Email, … are said to be the constructors of the corresponding type • Maybe, Either and Ordering are predefined in Haskell Haskell – Custom Type • You can use Notepad++ to write the code and save as “.hs” • Suppose your code is saved as “C:\Haskell\code\sample.hs” • You need to type the following to load the code into ghci :load C:\Haskell\code\sample.hs • You will see the “Prelude” become “Main” if it is loaded successfully Haskell – Custom Type • Phone and Email are constructors of Contact • They are also functions with the following type Haskell – Custom Type data Contact = Phone Integer | Email String data Maybe a = Just a | Nothing data Either a b = Left a | Right b data Ordering = LT | EQ | GT • Maybe, Either are kinds and NOT classes nor types • Contact, Maybe Int are types • Phone 98765432, Just 0, Nothing are values Haskell – Infix Function • A function with symbol only is assumed to be infix operator • Need to add a pair of brackets to make it like normal functions -- x + y == (+) x y • A function can become infix if it is wrapped by `` add x y = x + y -- add x y == x `add` y Haskell – Precedence and Associativity • Infix functions has lower precedence then normal functions • Normal functions are left associated • i.e. f a b == (f a) b • Associativity of infix functions depend on the function • Usually left associated • Some right associated functions: exponent, (.), ($) ($) :: (a -> b) -> a -> b -- trick: f $ g $ h x == f (g (h x)) /= ((f g) h) x == f g h x Haskell – Anonymous Function • In Haskell, it is able to define anonymous function using lambda expression. • Syntax: \var1 var2 … varn -> expression • The expression goes as far as possible • Remember to add parentheses • Example: \x -> x + 1 \x y -> x + y Haskell – Anonymous Function • Remember when will you use anonymous function in C++? sort(v.begin(), v.end(), [] (int x, int y) { return x > y; }); • You can also write something similar in Haskell • There is a sortBy function in Haskell (in the package Data.List) • To import Data.List into ghci, simply type import Data.List sort :: Ord a => [a] -> [a] sortBy :: (a -> a -> Ordering) -> [a] -> [a] Haskell – Anonymous Function sort [1, 4, 2, 3] -- [1, 2, 3, 4] sortBy (\x y -> negate x `compare` negate y) [1, 4, 2, 3] -- [4, 3, 2, 1] -- negate :: Num a => a -> a -- compare :: Ord a => a -> a -> Ordering -- *this is not the best way to define it, why? Haskell – Unary Functions • Actually all functions can be viewed as unary functions • How about (+) which takes two parameter? (+) :: Num a => a -> a -> a -- can be viewed as (+) :: Num a => a -> (a -> a) -- (+) x == \y -> x + y • (->) is right associative • (+) takes one input (number) and returns one output (function) Haskell – Partial Application • Consider add x y = x + y addTwo = add 2 • What is the type of addTwo? • This is called partial application. Haskell – Partial Application • Here comes some function that are often applied partially const :: a -> b -> a -- usually be viewed as const :: a -> (b -> a) flip :: (a -> b -> c) -> b -> a -> c -- usually be viewed as flip :: (a -> b -> c) -> (b -> a -> c) (.) :: (b -> c) -> (a -> b) -> a -> c -- usually be viewed as (.) :: (b -> c) -> (a -> b) -> (a -> c) -- aka.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    119 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us