Functional Programming Charlie Li 6/4/2019 Content

Total Page:16

File Type:pdf, Size:1020Kb

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.
Recommended publications
  • GHC Reading Guide
    GHC Reading Guide - Exploring entrances and mental models to the source code - Takenobu T. Rev. 0.01.1 WIP NOTE: - This is not an official document by the ghc development team. - Please refer to the official documents in detail. - Don't forget “semantics”. It's very important. - This is written for ghc 9.0. Contents Introduction 1. Compiler - Compilation pipeline - Each pipeline stages - Intermediate language syntax - Call graph 2. Runtime system 3. Core libraries Appendix References Introduction Introduction Official resources are here GHC source repository : The GHC Commentary (for developers) : https://gitlab.haskell.org/ghc/ghc https://gitlab.haskell.org/ghc/ghc/-/wikis/commentary GHC Documentation (for users) : * master HEAD https://ghc.gitlab.haskell.org/ghc/doc/ * latest major release https://downloads.haskell.org/~ghc/latest/docs/html/ * version specified https://downloads.haskell.org/~ghc/9.0.1/docs/html/ The User's Guide Core Libraries GHC API Introduction The GHC = Compiler + Runtime System (RTS) + Core Libraries Haskell source (.hs) GHC compiler RuntimeSystem Core Libraries object (.o) (libHsRts.o) (GHC.Base, ...) Linker Executable binary including the RTS (* static link case) Introduction Each division is located in the GHC source tree GHC source repository : https://gitlab.haskell.org/ghc/ghc compiler/ ... compiler sources rts/ ... runtime system sources libraries/ ... core library sources ghc/ ... compiler main includes/ ... include files testsuite/ ... test suites nofib/ ... performance tests mk/ ... build system hadrian/ ... hadrian build system docs/ ... documents : : 1. Compiler 1. Compiler Compilation pipeline 1. compiler The GHC compiler Haskell language GHC compiler Assembly language (native or llvm) 1. compiler GHC compiler comprises pipeline stages GHC compiler Haskell language Parser Renamer Type checker Desugarer Core to Core Core to STG STG to Cmm Assembly language Cmm to Asm (native or llvm) 1.
    [Show full text]
  • Pattern Matching
    Functional Programming Steven Lau March 2015 before function programming... https://www.youtube.com/watch?v=92WHN-pAFCs Models of computation ● Turing machine ○ invented by Alan Turing in 1936 ● Lambda calculus ○ invented by Alonzo Church in 1930 ● more... Turing machine ● A machine operates on an infinite tape (memory) and execute a program stored ● It may ○ read a symbol ○ write a symbol ○ move to the left cell ○ move to the right cell ○ change the machine’s state ○ halt Turing machine Have some fun http://www.google.com/logos/2012/turing-doodle-static.html http://www.ioi2012.org/wp-content/uploads/2011/12/Odometer.pdf http://wcipeg.com/problems/desc/ioi1211 Turing machine incrementer state symbol action next_state _____ state 0 __1__ state 1 0 _ or 0 write 1 1 _10__ state 2 __1__ state 1 0 1 write 0 2 _10__ state 0 __1__ state 0 _00__ state 2 1 _ left 0 __0__ state 2 _00__ state 0 __0__ state 0 1 0 or 1 right 1 100__ state 1 _10__ state 1 2 0 left 0 100__ state 1 _10__ state 1 100__ state 1 _10__ state 1 100__ state 1 _10__ state 0 100__ state 0 _11__ state 1 101__ state 1 _11__ state 1 101__ state 1 _11__ state 0 101__ state 0 λ-calculus Beware! ● think mathematical, not C++/Pascal ● (parentheses) are for grouping ● variables cannot be mutated ○ x = 1 OK ○ x = 2 NO ○ x = x + 1 NO λ-calculus Simplification 1 of 2: ● Only anonymous functions are used ○ f(x) = x2+1 f(1) = 12+1 = 2 is written as ○ (λx.x2+1)(1) = 12+1 = 2 note that f = λx.x2+1 λ-calculus Simplification 2 of 2: ● Only unary functions are used ○ a binary function can be written as a unary function that return another unary function ○ (λ(x,y).x+y)(1,2) = 1+2 = 3 is written as [(λx.(λy.x+y))(1)](2) = [(λy.1+y)](2) = 1+2 = 3 ○ this technique is known as Currying Haskell Curry λ-calculus ● A lambda term has 3 forms: ○ x ○ λx.A ○ AB where x is a variable, A and B are lambda terms.
    [Show full text]
  • Lambda Calculus and Functional Programming
    Global Journal of Researches in Engineering Vol. 10 Issue 2 (Ver 1.0) June 2010 P a g e | 47 Lambda Calculus and Functional Programming Anahid Bassiri1Mohammad Reza. Malek2 GJRE Classification (FOR) 080299, 010199, 010203, Pouria Amirian3 010109 Abstract-The lambda calculus can be thought of as an idealized, Basis concept of a Turing machine is the present day Von minimalistic programming language. It is capable of expressing Neumann computers. Conceptually these are Turing any algorithm, and it is this fact that makes the model of machines with random access registers. Imperative functional programming an important one. This paper is programming languages such as FORTRAN, Pascal etcetera focused on introducing lambda calculus and its application. As as well as all the assembler languages are based on the way an application dikjestra algorithm is implemented using a Turing machine is instructed by a sequence of statements. lambda calculus. As program shows algorithm is more understandable using lambda calculus in comparison with In addition functional programming languages, like other imperative languages. Miranda, ML etcetera, are based on the lambda calculus. Functional programming is a programming paradigm that I. INTRODUCTION treats computation as the evaluation of mathematical ambda calculus (λ-calculus) is a useful device to make functions and avoids state and mutable data. It emphasizes L the theories realizable. Lambda calculus, introduced by the application of functions, in contrast with the imperative Alonzo Church and Stephen Cole Kleene in the 1930s is a programming style that emphasizes changes in state. formal system designed to investigate function definition, Lambda calculus provides a theoretical framework for function application and recursion in mathematical logic and describing functions and their evaluation.
    [Show full text]
  • Purity in Erlang
    Purity in Erlang Mihalis Pitidis1 and Konstantinos Sagonas1,2 1 School of Electrical and Computer Engineering, National Technical University of Athens, Greece 2 Department of Information Technology, Uppsala University, Sweden [email protected], [email protected] Abstract. Motivated by a concrete goal, namely to extend Erlang with the abil- ity to employ user-defined guards, we developed a parameterized static analysis tool called PURITY, that classifies functions as referentially transparent (i.e., side- effect free with no dependency on the execution environment and never raising an exception), side-effect free with no dependencies but possibly raising excep- tions, or side-effect free but with possible dependencies and possibly raising ex- ceptions. We have applied PURITY on a large corpus of Erlang code bases and report experimental results showing the percentage of functions that the analysis definitely classifies in each category. Moreover, we discuss how our analysis has been incorporated on a development branch of the Erlang/OTP compiler in order to allow extending the language with user-defined guards. 1 Introduction Purity plays an important role in functional programming languages as it is a corner- stone of referential transparency, namely that the same language expression produces the same value when evaluated twice. Referential transparency helps in writing easy to test, robust and comprehensible code, makes equational reasoning possible, and aids program analysis and optimisation. In pure functional languages like Clean or Haskell, any side-effect or dependency on the state is captured by the type system and is reflected in the types of functions. In a language like ERLANG, which has been developed pri- marily with concurrency in mind, pure functions are not the norm and impure functions can freely be used interchangeably with pure ones.
    [Show full text]
  • Haskell-Like S-Expression-Based Language Designed for an IDE
    Department of Computing Imperial College London MEng Individual Project Haskell-Like S-Expression-Based Language Designed for an IDE Author: Supervisor: Michal Srb Prof. Susan Eisenbach June 2015 Abstract The state of the programmers’ toolbox is abysmal. Although substantial effort is put into the development of powerful integrated development environments (IDEs), their features often lack capabilities desired by programmers and target primarily classical object oriented languages. This report documents the results of designing a modern programming language with its IDE in mind. We introduce a new statically typed functional language with strong metaprogramming capabilities, targeting JavaScript, the most popular runtime of today; and its accompanying browser-based IDE. We demonstrate the advantages resulting from designing both the language and its IDE at the same time and evaluate the resulting environment by employing it to solve a variety of nontrivial programming tasks. Our results demonstrate that programmers can greatly benefit from the combined application of modern approaches to programming tools. I would like to express my sincere gratitude to Susan, Sophia and Tristan for their invaluable feedback on this project, my family, my parents Michal and Jana and my grandmothers Hana and Jaroslava for supporting me throughout my studies, and to all my friends, especially to Harry whom I met at the interview day and seem to not be able to get rid of ever since. ii Contents Abstract i Contents iii 1 Introduction 1 1.1 Objectives ........................................ 2 1.2 Challenges ........................................ 3 1.3 Contributions ...................................... 4 2 State of the Art 6 2.1 Languages ........................................ 6 2.1.1 Haskell ....................................
    [Show full text]
  • Deep Dive Into Programming with CAPS HMPP Dev-Deck
    Introduction to HMPP Hybrid Manycore Parallel Programming Московский государственный университет, Лоран Морен, 30 август 2011 Hybrid Software for Hybrid Hardware • The application should stay hardware resilient o New architectures / languages to master o Hybrid solutions evolve: we don‟t want to redo the work each time • Kernel optimizations are the key to get performance o An hybrid application must get the best of its hardware resources 30 август 2011 Москва - Лоран Морен 2 Methodology to Port Applications Methodology to Port Applications Hotspots Parallelization •Optimize CPU code •Performance goal •Exhibit Parallelism •Validation process •Move kernels to GPU •Hotspots selection •Continuous integration Define your Port your Hours to Days parallel application Days to Weeks project on GPU GPGPU operational Phase 1 application with known potential Phase 2 Tuning Optimize your GPGPU •Exploit CPU and GPU application •Optimize kernel execution •Reduce CPU-GPU data transfers Weeks to Months 30 август 2011 Москва - Лоран Морен 4 Take a decision • Go • Dense hotspot • Fast GPU kernels • Low CPU-GPU data transfers • Midterm perspective: Prepare to manycore parallelism • No Go o Flat profile o GPU results not accurate enough • cannot validate the computation o Slow GPU kernels • i.e. no speedup to be expected o Complex data structures o Big memory space requirement 30 август 2011 Москва - Лоран Морен 5 Tools in the Methodology Hotspots Parallelization • Profiling tools Gprof, Kachegrind, Vampir, Acumem, ThreadSpotter •HMPP Workbench •Debugging
    [Show full text]
  • A Formal Methodology for Deriving Purely Functional Programs from Z Specifications Via the Intermediate Specification Language Funz
    Louisiana State University LSU Digital Commons LSU Historical Dissertations and Theses Graduate School 1995 A Formal Methodology for Deriving Purely Functional Programs From Z Specifications via the Intermediate Specification Language FunZ. Linda Bostwick Sherrell Louisiana State University and Agricultural & Mechanical College Follow this and additional works at: https://digitalcommons.lsu.edu/gradschool_disstheses Recommended Citation Sherrell, Linda Bostwick, "A Formal Methodology for Deriving Purely Functional Programs From Z Specifications via the Intermediate Specification Language FunZ." (1995). LSU Historical Dissertations and Theses. 5981. https://digitalcommons.lsu.edu/gradschool_disstheses/5981 This Dissertation is brought to you for free and open access by the Graduate School at LSU Digital Commons. It has been accepted for inclusion in LSU Historical Dissertations and Theses by an authorized administrator of LSU Digital Commons. For more information, please contact [email protected]. INFORMATION TO USERS This manuscript has been reproduced from the microfilm master. UMI films the text directly from the original or copy submitted. Thus, some thesis and dissertation copies are in typewriter face, while others may be from any type of computer printer. H ie quality of this reproduction is dependent upon the quality of the copy submitted. Broken or indistinct print, colored or poor quality illustrations and photographs, print bleedthrough, substandardm argins, and improper alignment can adversely affect reproduction. In the unlikely, event that the author did not send UMI a complete manuscript and there are missing pages, these will be noted. Also, if unauthorized copyright material had to be removed, a note will indicate the deletion. Oversize materials (e.g., maps, drawings, charts) are reproduced by sectioning the original, beginning at the upper left-hand comer and continuing from left to right in equal sections with small overlaps.
    [Show full text]
  • The Logic of Demand in Haskell
    Under consideration for publication in J. Functional Programming 1 The Logic of Demand in Haskell WILLIAM L. HARRISON Department of Computer Science University of Missouri Columbia, Missouri RICHARD B. KIEBURTZ Pacific Software Research Center OGI School of Science & Engineering Oregon Health & Science University Abstract Haskell is a functional programming language whose evaluation is lazy by default. However, Haskell also provides pattern matching facilities which add a modicum of eagerness to its otherwise lazy default evaluation. This mixed or “non-strict” semantics can be quite difficult to reason with. This paper introduces a programming logic, P-logic, which neatly formalizes the mixed evaluation in Haskell pattern-matching as a logic, thereby simplifying the task of specifying and verifying Haskell programs. In P-logic, aspects of demand are reflected or represented within both the predicate language and its model theory, allowing for expressive and comprehensible program verification. 1 Introduction Although Haskell is known as a lazy functional language because of its default eval- uation strategy, it contains a number of language constructs that force exceptions to that strategy. Among these features are pattern-matching, data type strictness annotations and the seq primitive. The semantics of pattern-matching are further enriched by irrefutable pattern annotations, which may be embedded within pat- terns. The interaction between Haskell’s default lazy evaluation and its pattern- matching is surprisingly complicated. Although it offers the programmer a facility for fine control of demand (Harrison et al., 2002), it is perhaps the aspect of the Haskell language least well understood by its community of users. In this paper, we characterize the control of demand first in a denotational semantics and then in a verification logic called “P-logic”.
    [Show full text]
  • The Quantum IO Monad Thorsten Altenkirch and Alexander S
    1 The Quantum IO Monad Thorsten Altenkirch and Alexander S. Green School of Computer Science, The University of Nottingham Abstract The Quantum IO monad is a purely functional interface to quantum programming implemented as a Haskell library. At the same time it provides a constructive semantics of quantum programming. The QIO monad separates reversible (i.e. unitary) and irreversible (i.e. prob- abilistic) computations and provides a reversible let operation (ulet), allowing us to use ancillas (auxiliary qubits) in a modular fashion. QIO programs can be simulated either by calculating a probability distribu- tion or by embedding it into the IO monad using the random number generator. As an example we present a complete implementation of Shor’s algorithm. 1.1 Introduction We present an interface from a pure functional programming language, Haskell, to quantum programming: the Quantum IO monad, and use it to implement Shor’s factorisation algorithm. The implementation of the QIO monad provides a constructive semantics for quantum programming, i.e. a functional program which can also be understood as a mathematical model of quantum computing. Actually, the Haskell QIO library is only a first approximation of such a semantics, we would like to move to a more expressive language which is also logically sound. Here we are thinking of a language like Agda (Norell (2007)), which is based on Martin L¨of’s Type Theory. We have already investigated this approach of functional specifications of effects in a classical context (Swierstra and Altenkirch (2007, 2008); Swierstra (2008)). At the same 1 2 Thorsten Altenkirch and Alexander S.
    [Show full text]
  • Why Functional Programming Is Good … …When You Like Math - Examples with Haskell
    Why functional programming is good … …when you like math - examples with Haskell . Jochen Schulz Georg-August Universität Göttingen 1/18 Table of contents 1. Introduction 2. Functional programming with Haskell 3. Summary 1/18 Programming paradigm imperative (e.g. C) object-oriented (e.g. C++) functional (e.g. Haskell) (logic) (symbolc) some languages have multiple paradigm 2/18 Side effects/pure functions . side effect . Besides the return value of a function it has one or more of the following modifies state. has observable interaction with outside world. pure function . A pure function always returns the same results on the same input. has no side-effect. .also refered to as referential transparency pure functions resemble mathematical functions. 3/18 Functional programming emphasizes pure functions higher order functions (partial function evaluation, currying) avoids state and mutable data (Haskell uses Monads) recursion is mostly used for loops algebraic type system strict/lazy evaluation (often lazy, as Haskell) describes more what is instead what you have to do 4/18 Table of contents 1. Introduction 2. Functional programming with Haskell 3. Summary 5/18 List comprehensions Some Math: S = fx2jx 2 N; x2 < 20g > [ x^2 | x <- [1..10] , x^2 < 20 ] [1,4,9,16] Ranges (and infinite ranges (don’t do this now) ) > a = [1..5], [1,3..8], ['a'..'z'], [1..] [1,2,3,4,5], [1,3,5,7], "abcdefghijklmnopqrstuvwxyz" usually no direct indexing (needed) > (head a, tail a, take 2 a, a !! 2) (1,[2,3,4,5],[1,2],3) 6/18 Functions: Types and Typeclasses Types removeNonUppercase :: [Char] -> [Char] removeNonUppercase st = [ c | c <- st, c `elem ` ['A'..'Z']] Typeclasses factorial :: (Integral a) => a -> a factorial n = product [1..n] We also can define types and typeclasses and such form spaces.
    [Show full text]
  • Function Programming in Python
    Functional Programming in Python David Mertz Additional Resources 4 Easy Ways to Learn More and Stay Current Programming Newsletter Get programming related news and content delivered weekly to your inbox. oreilly.com/programming/newsletter Free Webcast Series Learn about popular programming topics from experts live, online. webcasts.oreilly.com O’Reilly Radar Read more insight and analysis about emerging technologies. radar.oreilly.com Conferences Immerse yourself in learning at an upcoming O’Reilly conference. conferences.oreilly.com ©2015 O’Reilly Media, Inc. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. #15305 Functional Programming in Python David Mertz Functional Programming in Python by David Mertz Copyright © 2015 O’Reilly Media, Inc. All rights reserved. Attribution-ShareAlike 4.0 International (CC BY-SA 4.0). See: http://creativecommons.org/licenses/by-sa/4.0/ Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or [email protected]. Editor: Meghan Blanchette Interior Designer: David Futato Production Editor: Shiny Kalapurakkel Cover Designer: Karen Montgomery Proofreader: Charles Roumeliotis May 2015: First Edition Revision History for the First Edition 2015-05-27: First Release The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Functional Pro‐ gramming in Python, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc.
    [Show full text]
  • What Is Functional Programming? by by Luis Atencio
    What is Functional Programming? By By Luis Atencio Functional programming is a software development style with emphasis on the use functions. It requires you to think a bit differently about how to approach tasks you are facing. In this article, based on the book Functional Programming in JavaScript, I will introduce you to the topic of functional programming. The rapid pace of web platforms, the evolution of browsers, and, most importantly, the demand of your end users has had a profound effect in the way we design web applications today. Users demand web applications feel more like a native desktop or mobile app so that they can interact with rich and responsive widgets, which forces JavaScript developers to think more broadly about the solution domain push for adequate programming paradigms. With the advent of Single Page Architecture (SPA) applications, JavaScript developers began jumping into object-oriented design. Then, we realized embedding business logic into the client side is synonymous with very complex JavaScript applications, which can get messy and unwieldy very quickly if not done with proper design and techniques. As a result, you easily accumulate lots of entropy in your code, which in turn makes your application harder write, test, and maintain. Enter Functional Programming. Functional programming is a software methodology that emphasizes the evaluation of functions to create code that is clean, modular, testable, and succinct. The goal is to abstract operations on the data with functions in order to avoid side effects and reduce mutation of state in your application. However, thinking functionally is radically different from thinking in object-oriented terms.
    [Show full text]