Introduction to Functional Programming and Scripting (Exam Revision) John Woodward

Size: px
Start display at page:

Download "Introduction to Functional Programming and Scripting (Exam Revision) John Woodward"

Transcription

1 Introduction to Functional Programming and Scripting (Exam Revision) John Woodward

2 Functional Programming Immutable, Stateless (good news?) Function are first class objects (higher order functions). Programs in functional languages are generally shorter, easier to understand, design, debug, and maintain, than imperative counterpart. Modern functional languages are strongly typed. guarantees no type errors at runtime (trapped by the compiler). Type Inference Typically recursion is used in functional programming languages, iteration is used in imperative languages.

3 State & Referential Transparency Java object store state information (instance variables). E.g. in a constructor Person( John, 45, UK, Lecturer ). This stores Name, Age, Nationality, Job Print Function_A(x) Print Function_B(x) Print Function_A(x) (side effects).

4 Data Type and Type Signatures In maths a function f maps between two sets A and B type signature A->B (domain and codomain, input and output) type signatures. (Boolean, real, float, natural, integers, ) B,R, F, N, Z, (a pair of Booleans) BXB or B^2 Type inference can be used to infer facts about types. e.g. composition - theorems for free

5 Higher Order Functions (HOF) In most programming languages we pass around integers, Booleans, strings, as argument to function and return types For example Boolean isprime(integer n) Takes an integer and returns true/false depending on if it is prime or not. With functional languages we can pass around functions. Type signatures

6 Naming a String String name = John Print(name);//will print John Or we can just print the name directly Print( John ) If we only use John once we could use a string literal (a one-off use). If we use John multiple times define a variable name and use that.

7 Anonymous Functions/lambda (PYTHON) def f (x): return x**2 print f(8) Or we can do g = lambda x: x**2 print g(8) Or just do it directly print (lambda x: x+2) (4) y = (lambda x: x*2) (4) print y

8 Anonymous Functions (SCALA) println(((a: Int) => a + 1)(4)) An increment function with the argument 4 println(((a: Int, b: Int) => a + b)(4, 6)) The addition function with the arguments 4 and 6.

9 Lambda filter, map, reduce (PYTHON) nums= [2, 18, 9, 22, 17, 24, 8, 12, 27] print filter(lambda x: x % 3 == 0, nums) #[18, 9, 24, 12, 27] print map(lambda x: x * , nums) #[14, 46, 28, 54, 44, 58, 26, 34, 64] print reduce(lambda x, y: x + y, nums) #139 (more detail in a few slides)

10 Lambda filter, map, reduce (SCALA) nums = [2, 18, 9, 22, 17, 24, 8, 12, 27] println(nums.filter((x: Int) => x % 3 == 0)) //[18, 9, 24, 12, 27] println(nums.map((x: Int) => x*2+10)) //[14, 46, 28, 54, 44, 58, 26, 34, 64] println(nums.reduce((a:int, b:int)=>a+b)) #139 (more detail in a few slides)

11 Simple example: Higher order Function (Python) Takes a function f and value x and evaluates f(x), returning the result. def apply(f, x): return f(x)

12 Simple example: Higher order Function (Scala) //Takes a function f and value x and //evaluates f(x), returning the //result. def apply(f:int=>int, x:int):int = { f(x) }

13 f(x) and f In maths f and f(x) are different. f is a function! f(x) is the value of f at value x Never say the function f(x) Say - The function f that takes a variable x (i.e. f takes var x) Or the function f at the points x (i.e. f given x has the value??)

14 Example: A linear function (PYTHON) #return a function #note return result, not result(x) def linear(a, b): def result(x): return a*x + b return result mylinearfunction = linear(4,3) #make a function 4*x+3 print mylinearfunction(8) print apply(mylinearfunction, 8)

15 Example: A linear function (SCALA) //return a function def linear(a: Double, b: Double): Double => Double = { x:double => a*x + b }mylinearfunction = linear(4,3) //make a function?*?+? println(linear(2,1)(9))

16 Summation (PYTHON) i=10 i=1 In maths f(x) = f(1)+f(2)+ +f(10) takes 3 arguments, and upper and lower bound and a function to sum over. i=10 e.g. i=1 2x = =2+4+6=12 def sum(f, a, b): total = 0 for i in range(a, b+1): total += f(i) return total

17 Summation (SCALA) i=10 i=1 In maths f(x) = f(1)+f(2)+ +f(10) takes 3 arguments, and upper and lower bound and a function to sum over. i=10 e.g. i=1 2x = =2+4+6=12 def sum(f: Int => Int, a: Int, b: Int): Int = { if (a > b) 0 else f(a) + sum(f, a + 1, b) }

18 Some simple functions def timesone(x): return 1*x def timestwo(x): return 2*x def timesthree(x): return 3*x def apply(f, x): return f(x)

19 Returning a Function (PYTHON) def compositionfunction(f, g): def result(x): return f(g(x)) return result myfunction = compositionfunction(timesthree, timestwo) print myfunction(4) print apply(compositionfunction(timesthree, timestwo), 4) print (lambda x, y :compositionfunction(x,y)) (timesthree, timestwo) (4)

20 Returning a Function (SCALA) def compositionfunction(f: Int => Int, g: Int => Int): Int => Int = { x: Int => f(g(x)) }

21 Maximum of two function (PYTHON) We can find the max of two functions (PICTURE) def maximumvalue(f1, f2, x): return max(f1(x), f2(x)) #The inputs are??? #The output is??? #what is the data-type signature #Can we return a function? #What is the signature of the returned function

22 Returning the Max Function (PYTHON) def maxfunction(f1, f2): def maxfun(x): return max(f1(x), f2(x)) return maxfun biggerfun = maxfunction(fun1, fun2) print biggerfun(2)

23 Max Function (SCALA) def maxfunction(f: Int => Int, g: Int => Int): Int => Int = { x: Int => { if (f(x) > g(x)) f(x) else g(x) } }

24 Partial Application Motivating example - diagram Addition (+) takes two arguments (arg1 + arg2) What if we only supply one argument? We cannot compute e.g. (1+) 1+WHAT But (1+) is a function of one argument (1+ could be called what???)

25 Inc as partial add (PYTHON) #add (2 args), inc(x)=add(1,x) #inc is a special case of add from functools import partial def add(a,b): return a+b inc = partial(add, 1) print inc(4)

26 Inc as partial add (SCALA) def add(a:int, b:int):int = { a+b } val inc = add(1, _: Int) def incfun: Int=>Int = { x: Int => add(x,1) } print(incfun(4))

27 double as partial mul (PYTHON) #mul(2 args), double(x)=mul(2,x) #double is a special case of mul from functools import partial def mul(a,b): return a*b double = partial(mul, 2) print double(10)

28 referential transparency Haskell is a pure functional language referential transparency - the evaluation of an expression does not depend on context. The value of an expression can be evaluated in any order (all sequences that terminate return the same value) (1+2)+(3+4) we could reduce this in any order. In the 2nd world war, Richard Feynman was in charge of making calculation for the atomic bomb project. These calculations were done by humans working in parallel. e.g. calculate exponential

29 Map, Filter, Reduce Let us now look at 3 higher order functions which are used a lot in functional programming. First we will look LISTs Then we will look at Map, Filter and Reduce.

30 Map - Scala Map applies a function to each element in a list var nums: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9) println(nums.map(x => x * x * x)) Will print what???

31 answer List(3, 4, 5, 6, 7, 8, 9, 10, 11)

32 Filter (Exercise) Scala Filter pass only elements of the list which pass a test var nums: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9) println(nums.filter(x => x % 2 == 1)) println(nums.filter(x => x % 3 == 2)) println(nums.filter(x => (x % 2 == 0) (x % 3 == 2)))

33 Filter (answers) Scala println(nums.filter(x => x % 2 == 1)) List(1, 3, 5, 7, 9) println(nums.filter(x => x % 3 == 2)) List(2, 5, 8) println(nums.filter(x => (x % 2 == 0) (x % 3 == 2))) List(2, 4, 5, 6, 8)

34 How does reduce work? //what does the following print def add(x: Int, y: Int): Int = { println(x + " " + y) x + y } nums = List(1, 2, 3, 4) println(nums.reduce(add)) //=1*2*3*4

35 Answer - add //try with mul (*), sub(-) def mul(x: Int, y: Int): Int = { println(x + " " + y) x * y }

36 Answer - mul var nums: List[Int] = List(1, 2, 3, 4) println(nums.reduce(mul))

37 Answer sub var nums: List[Int] = List(1, 2, 3, 4) println(nums.reduce(sub))

38 fold Fold does the same as reduce except we can pass in a starting value. var nums: List[Int] = List(1, 2, 3, 4) println(nums.reduce(add)) println(nums.fold(1)(add)) println(nums.reduce(mul)) println(nums.fold(1)(mul)) println(nums.fold(0)(mul))

39 Fold - answers

40 combinations println( nums.map(x=>x+2).filter(x => x % 2==0)) println( nums.map(x=>x+3).fold(0)(add)) Answers List(4, 6) 22

41 SCRIPTING LANGUAGES

42 Scripting Languages

43 Basics proper programmers write commands E.g. mkdir john1 rather than clicking on icons If you write a (set of) command more that once you can put them in a file and you do not need to write them again. Two of more, use a for (Dijkstra) Interpreted not compiled (like java) Automate the execution of tasks Glue or high level languages.

44 Scripting language 1 Scripting languages are designed to automate frequently used tasks that usually involve calling or passing commands to external programs. Those that are interpretive are often called scripting languages. In the following slides (py means python and sh means bash)

45 Scripting language 2 Recently, many applications have built-in traditional scripting languages, such as Perl or Visual Basic, but there are quite a few "native" scripting languages still in use. Many scripting languages are compiled to bytecode and then this (usually) platform independent bytecode is run through a virtual machine (compare to Java).

46 Examples of Scripting Langauges Bash (unix/linux) Cygwin (windows freely downloadable) Python (adopted by BIG DATA communities) perl "script" often used for small programs (up to a few thousand lines of code) text-processing languages sed and AWK Nothing special about scripting languages

47 What you see

48 Working with Files cp <filename> <new filename> copy - Make a copy of a file cp -R <directory> <new directory> Make a copy of a directory mv <filename> <new filename> move - Move or rename a file rm <filename> remove - Delete a file 48

49 Some Bash/cygwin Commands 2 echo "hi" # prints hi to screen echo "hi" > file.txt #writes hi to file.txt (overwrite) echo "bye" >> file.txt #writes bye to file.txt (appends) read usermessage #asks user for message head -2 file.txt #prints first two lines of file.txt tail -2 file.txt #prints last two lines of file.txt

50 Spaces and $ (values of) (sh) todo jrw@tambala ~ $ x= 8 -bash: 8: command not found jrw@tambala ~ $ x=8 jrw@tambala ~ $ echo $x 8 jrw@tambala ~ $ echo x x jrw@tambala ~ $

51 Input/Output (py) userinput = raw_input( Type in a any input') print You typed "+userinput Gives output Type in a any input: this is my input You typed: this is my input #cf. java

52 Exec command (py, sh) Many scripting languages treat the programs as text strings. Therefore you can construct a string and execute it. mycmd = "print 'hi'" exec mycmd

53 Eval (py) userequation= raw_input('type in a simple maths equation in one variable x e.g. x+1') print "you typed "+userequation x = raw_input('type in an integer value for x') print "x is "+ x x = int(x) y = eval(userequation) print y

54 Improved (py) userequation= raw_input('type in a simple maths equation in one variable x e.g. x+1') print "you typed "+userequation x = raw_input('type in a positive integer value for x: ') print "x is "+ str(x) if (x.isdigit()):#chech is it a positive integer x = int(x) y = eval(userequation) print y else: print "you did not enter a number"

55 Example output type in a simple maths equation in one variable x e.g. x+1: x**2+1 you typed x**2+1 type in a positive integer value for x: 3 x is 3 10

56 Question How easy is that to do in java? Could you do it? Can the program be improved? E.g. how do we know the user types in a mathematical expression??? What is dangerous about the exec command?

57 More Scripting A program (java, python) is just a text file. We can manipulate text files easily (with python, sh) Therefore we can manipulate programs themselves. This is my research areas ask me for details

58 Summary Scripts are interpreted. Good for repeated tasks. We covered some basic commands. You can use them to glue other programs together

59 Regular Expressions (in Python)

60 Python or Egrep We will use Python. In some scripting languages you can call the command grep or egrep egrep pattern file.txt E.g. egrep ^A file.txt Will print all the line of file.txt which start with (^) the letter A (capital A)

61 Regular expression (abbreviated regex or regexp) a search pattern, mainly for use in pattern matching with strings, i.e. "find and replace"- like operations. Each character in a regular expression is either understood to be a metacharacter with its special meaning, or a regular character with its literal meaning. We ask the question does a given string match a certain pattern?

62 List of Meta characters. a single character + one or more of the preceding element? zero or one of the preceding element * zero or more of the preceding element ^ Matches the starting position within the string $ Matches the ending position of the string or the position just before a string-ending newline []Matches a single character that is contained within the brackets [^...] exceptions. [^b]at matches all strings matched by.at except "bat". or () grouping {m,n} Matches the preceding element at least m and not more than n times

63 -v option egrep -v pattern file.txt -v is a extra option It inverts the matching, and matches everything NOT matched by the pattern.

64 e.g. Username /^[a-z0-9_-]{3,16}$/ Starts and ends with 3-16 numbers, letters, underscores or hyphens Any lowercase letter (a-z), number (0-9), an underscore, or a hyphen. At least 3 to 16 characters. Matches E.g. my-us3r_n4m3 but not th1s1swayt00_l0ngt0beausername

65 e.g. Password /^[a-z0-9_-]{6,18}$/ Starts and ends with 6-18 letters, numbers, underscores, hyphens. Matches e.g. myp4ssw0rd but not mypa$$w0rd

66 e.g. Hex Value /^#?([a-f0-9]{6} [a-f0-9]{3})$/ Starts with a +/- (optional) followed by one or more Matches e.g. #a3c113 but not #4d82h4

67 e.g. String that matches: String that doesn't match: (TLD is too long)

68 Match n characters egrep.exe "^...$" data1.txt Will match any line with exactly 3 characters ^ starts with. And contains (i.e. 3 characters) $ ends with Or just egrep.exe "^.{3}$" data1.txt What about egrep.exe "(..){2}" data1.txt?

Introduction to Functional Programming (Python) John R. Woodward

Introduction to Functional Programming (Python) John R. Woodward Introduction to Functional Programming (Python) John R. Woodward Functional Programming 1. Programming paradigm? Object oriented, imperative 2. Immutable state (referential transparency) 3. Higher order

More information

Basics. proper programmers write commands

Basics. proper programmers write commands Scripting Languages Basics proper programmers write commands E.g. mkdir john1 rather than clicking on icons If you write a (set of) command more that once you can put them in a file and you do not need

More information

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017 Introduction to Concepts in Functional Programming CS16: Introduction to Data Structures & Algorithms Spring 2017 Outline Functions State Functions as building blocks Higher order functions Map Reduce

More information

Functional programming

Functional programming Functional programming Functional programming In functional programming, functions are the core building blocks In pure functional programming, functions are like mathematical functions Mathematical functions

More information

Algorithms and Programming I. Lecture#12 Spring 2015

Algorithms and Programming I. Lecture#12 Spring 2015 Algorithms and Programming I Lecture#12 Spring 2015 Think Python How to Think Like a Computer Scientist By :Allen Downey Installing Python Follow the instructions on installing Python and IDLE on your

More information

Introduction to Functional Programming in Haskell 1 / 56

Introduction to Functional Programming in Haskell 1 / 56 Introduction to Functional Programming in Haskell 1 / 56 Outline Why learn functional programming? The essence of functional programming What is a function? Equational reasoning First-order vs. higher-order

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Basics

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Basics 1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Basics 2 Contents 1. Jump into Haskell: Using ghc and ghci (more detail) 2. Historical Background of Haskell 3. Lazy, Pure, and Functional

More information

Functional Programming. Big Picture. Design of Programming Languages

Functional Programming. Big Picture. Design of Programming Languages Functional Programming Big Picture What we ve learned so far: Imperative Programming Languages Variables, binding, scoping, reference environment, etc What s next: Functional Programming Languages Semantics

More information

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.)

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.) Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.) David Haraburda January 30, 2013 1 Introduction Scala is a multi-paradigm language that runs on the JVM (is totally

More information

CSCE 314 Programming Languages

CSCE 314 Programming Languages CSCE 314 Programming Languages Haskell 101 Dr. Hyunyoung Lee 1 Contents 1. Historical Background of Haskell 2. Lazy, Pure, and Functional Language 3. Using ghc and ghci 4. Functions 5. Haskell Scripts

More information

functional programming in Python, part 2

functional programming in Python, part 2 Programming Languages Week 2 functional programming in Python, part 2 College of Information Science and Engineering Ritsumeikan University review of part 1 eliminating assignment makes programs easier

More information

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement Outline Expression Evaluation and Control Flow In Text: Chapter 6 Notation Operator evaluation order Operand evaluation order Overloaded operators Type conversions Short-circuit evaluation of conditions

More information

Programming Systems in Artificial Intelligence Functional Programming

Programming Systems in Artificial Intelligence Functional Programming Click to add Text Programming Systems in Artificial Intelligence Functional Programming Siegfried Nijssen 8/03/16 Discover thediscover world at the Leiden world University at Leiden University Overview

More information

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc. CSC312 Principles of Programming Languages : Functional Programming Language Overview of Functional Languages They emerged in the 1960 s with Lisp Functional programming mirrors mathematical functions:

More information

CSc 372. Comparative Programming Languages. 4 : Haskell Basics. Department of Computer Science University of Arizona

CSc 372. Comparative Programming Languages. 4 : Haskell Basics. Department of Computer Science University of Arizona 1/40 CSc 372 Comparative Programming Languages 4 : Haskell Basics Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2013 Christian Collberg 2/40 The Hugs Interpreter The

More information

CS 360 Programming Languages Interpreters

CS 360 Programming Languages Interpreters CS 360 Programming Languages Interpreters Implementing PLs Most of the course is learning fundamental concepts for using and understanding PLs. Syntax vs. semantics vs. idioms. Powerful constructs like

More information

Defining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona

Defining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona Defining Functions CSc 372 Comparative Programming Languages 5 : Haskell Function Definitions Department of Computer Science University of Arizona collberg@gmail.com When programming in a functional language

More information

SD314 Outils pour le Big Data

SD314 Outils pour le Big Data Institut Supérieur de l Aéronautique et de l Espace SD314 Outils pour le Big Data Functional programming in Python Christophe Garion DISC ISAE Christophe Garion SD314 Outils pour le Big Data 1/ 35 License

More information

28-Nov CSCI 2132 Software Development Lecture 33: Shell Scripting. 26 Shell Scripting. Faculty of Computer Science, Dalhousie University

28-Nov CSCI 2132 Software Development Lecture 33: Shell Scripting. 26 Shell Scripting. Faculty of Computer Science, Dalhousie University Lecture 33 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 33: Shell Scripting 28-Nov-2018 Location: Chemistry 125 Time: 12:35 13:25 Instructor: Vla Keselj

More information

Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell

Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell Ori Bar El Maxim Finkel 01/11/17 1 History Haskell is a lazy, committee designed, pure functional programming language that

More information

Table of contents. Our goal. Notes. Notes. Notes. Summer June 29, Our goal is to see how we can use Unix as a tool for developing programs

Table of contents. Our goal. Notes. Notes. Notes. Summer June 29, Our goal is to see how we can use Unix as a tool for developing programs Summer 2010 Department of Computer Science and Engineering York University Toronto June 29, 2010 1 / 36 Table of contents 1 2 3 4 2 / 36 Our goal Our goal is to see how we can use Unix as a tool for developing

More information

sottotitolo A.A. 2016/17 Federico Reghenzani, Alessandro Barenghi

sottotitolo A.A. 2016/17 Federico Reghenzani, Alessandro Barenghi Titolo presentazione Piattaforme Software per la Rete sottotitolo BASH Scripting Milano, XX mese 20XX A.A. 2016/17, Alessandro Barenghi Outline 1) Introduction to BASH 2) Helper commands 3) Control Flow

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2016 Lecture 6a Andrew Tolmach Portland State University 1994-2016 Functional Programming An alternative paradigm to imperative programming First-class functions Emphasis

More information

Scala : an LLVM-targeted Scala compiler

Scala : an LLVM-targeted Scala compiler Scala : an LLVM-targeted Scala compiler Da Liu, UNI: dl2997 Contents 1 Background 1 2 Introduction 1 3 Project Design 1 4 Language Prototype Features 2 4.1 Language Features........................................

More information

CPS 506 Comparative Programming Languages. Programming Language Paradigm

CPS 506 Comparative Programming Languages. Programming Language Paradigm CPS 506 Comparative Programming Languages Functional Programming Language Paradigm Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming

More information

Scripting Languages Course 1. Diana Trandabăț

Scripting Languages Course 1. Diana Trandabăț Scripting Languages Course 1 Diana Trandabăț Master in Computational Linguistics - 1 st year 2017-2018 Today s lecture Introduction to scripting languages What is a script? What is a scripting language

More information

Chapter 15. Functional Programming Languages

Chapter 15. Functional Programming Languages Chapter 15 Functional Programming Languages Copyright 2009 Addison-Wesley. All rights reserved. 1-2 Chapter 15 Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages

More information

lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions

lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions Outline 1 Guessing Secrets functions returning functions oracles and trapdoor functions 2 anonymous functions lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions

More information

CSc 372 Comparative Programming Languages. 4 : Haskell Basics

CSc 372 Comparative Programming Languages. 4 : Haskell Basics CSc 372 Comparative Programming Languages 4 : Haskell Basics Christian Collberg Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2011 Christian Collberg August 23, 2011

More information

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program

More information

More Lambda Calculus and Intro to Type Systems

More Lambda Calculus and Intro to Type Systems More Lambda Calculus and Intro to Type Systems Plan Heavy Class Participation Thus, wake up! Lambda Calculus How is it related to real life? Encodings Fixed points Type Systems Overview Static, Dyamic

More information

CIS 194: Homework 3. Due Wednesday, February 11, Interpreters. Meet SImPL

CIS 194: Homework 3. Due Wednesday, February 11, Interpreters. Meet SImPL CIS 194: Homework 3 Due Wednesday, February 11, 2015 Interpreters An interpreter is a program that takes another program as an input and evaluates it. Many modern languages such as Java 1, Javascript,

More information

CS 301. Lecture 05 Applications of Regular Languages. Stephen Checkoway. January 31, 2018

CS 301. Lecture 05 Applications of Regular Languages. Stephen Checkoway. January 31, 2018 CS 301 Lecture 05 Applications of Regular Languages Stephen Checkoway January 31, 2018 1 / 17 Characterizing regular languages The following four statements about the language A are equivalent The language

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

PROGRAMMING IN HASKELL. Chapter 2 - First Steps PROGRAMMING IN HASKELL Chapter 2 - First Steps 0 The Hugs System Hugs is an implementation of Haskell 98, and is the most widely used Haskell system; The interactive nature of Hugs makes it well suited

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 4 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

An introduction introduction to functional functional programming programming using usin Haskell

An introduction introduction to functional functional programming programming using usin Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dkau Haskell The most popular p purely functional, lazy programming g language Functional programming language : a program

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 4 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

CS Unix Tools & Scripting

CS Unix Tools & Scripting Cornell University, Spring 2014 1 February 24, 2014 1 Slides evolved from previous versions by Hussam Abu-Libdeh and David Slater A note on awk for (item in array) The order in which items are returned

More information

Concepts of Programming Languages

Concepts of Programming Languages Concepts of Programming Languages Lecture 15 - Functional Programming Patrick Donnelly Montana State University Spring 2014 Patrick Donnelly (Montana State University) Concepts of Programming Languages

More information

! The simplest building blocks of a language. ! Compound elements are built from simpler ones

! The simplest building blocks of a language. ! Compound elements are built from simpler ones The Elements of Programming Primitive Expressions and Statements! The simplest building blocks of a language 61 Lecture Monday, ugust 9 Means of Combination! Compound elements are built from simpler ones

More information

And Parallelism. Parallelism in Prolog. OR Parallelism

And Parallelism. Parallelism in Prolog. OR Parallelism Parallelism in Prolog And Parallelism One reason that Prolog is of interest to computer scientists is that its search mechanism lends itself to parallel evaluation. In fact, it supports two different kinds

More information

CS 11 Haskell track: lecture 1

CS 11 Haskell track: lecture 1 CS 11 Haskell track: lecture 1 This week: Introduction/motivation/pep talk Basics of Haskell Prerequisite Knowledge of basic functional programming e.g. Scheme, Ocaml, Erlang CS 1, CS 4 "permission of

More information

CSc 372. Comparative Programming Languages. 2 : Functional Programming. Department of Computer Science University of Arizona

CSc 372. Comparative Programming Languages. 2 : Functional Programming. Department of Computer Science University of Arizona 1/37 CSc 372 Comparative Programming Languages 2 : Functional Programming Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2013 Christian Collberg 2/37 Programming Paradigms

More information

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled Interpreted vs Compiled Python 1 Java Interpreted Easy to run and test Quicker prototyping Program runs slower Compiled Execution time faster Virtual Machine compiled code portable Java Compile > javac

More information

Regexp. Lecture 26: Regular Expressions

Regexp. Lecture 26: Regular Expressions Regexp Lecture 26: Regular Expressions Regular expressions are a small programming language over strings Regex or regexp are not unique to Python They let us to succinctly and compactly represent classes

More information

Values (a.k.a. data) representation. Advanced Compiler Construction Michel Schinz

Values (a.k.a. data) representation. Advanced Compiler Construction Michel Schinz Values (a.k.a. data) representation Advanced Compiler Construction Michel Schinz 2016 03 10 The problem Values representation A compiler must have a way of representing the values of the source language

More information

Values (a.k.a. data) representation. The problem. Values representation. The problem. Advanced Compiler Construction Michel Schinz

Values (a.k.a. data) representation. The problem. Values representation. The problem. Advanced Compiler Construction Michel Schinz Values (a.k.a. data) representation The problem Advanced Compiler Construction Michel Schinz 2016 03 10 1 2 Values representation The problem A compiler must have a way of representing the values of the

More information

More Lambda Calculus and Intro to Type Systems

More Lambda Calculus and Intro to Type Systems More Lambda Calculus and Intro to Type Systems #1 One Slide Summary The lambda calculus is a model of computation or a programming language that is as expressive as a Turing machine. The lambda calculus

More information

Functional Languages. Hwansoo Han

Functional Languages. Hwansoo Han Functional Languages Hwansoo Han Historical Origins Imperative and functional models Alan Turing, Alonzo Church, Stephen Kleene, Emil Post, etc. ~1930s Different formalizations of the notion of an algorithm

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages CS 314 Principles of Programming Languages Lecture 16: Functional Programming Zheng (Eddy Zhang Rutgers University April 2, 2018 Review: Computation Paradigms Functional: Composition of operations on data.

More information

Common File System Commands

Common File System Commands Common File System Commands ls! List names of all files in current directory ls filenames! List only the named files ls -t! List in time order, most recent first ls -l! Long listing, more information.

More information

CS457/557 Functional Languages

CS457/557 Functional Languages CS457/557 Functional Languages Spring 2018 Lecture 1: Course Introduction Andrew Tolmach Portland State University (with thanks to Mark P. Jones) 1 Goals of this course Introduce the beautiful ideas of

More information

Lecture 13 CIS 341: COMPILERS

Lecture 13 CIS 341: COMPILERS Lecture 13 CIS 341: COMPILERS Announcements HW4: OAT v. 1.0 Parsing & basic code generation Due: March 28 th START EARLY! Midterm Exam Grades Available on Gradescope Zdancewic CIS 341: Compilers 2 Midterm

More information

Using Scala in CS241

Using Scala in CS241 Using Scala in CS241 Winter 2018 Contents 1 Purpose 1 2 Scala 1 3 Basic Syntax 2 4 Tuples, Arrays, Lists and Vectors in Scala 3 5 Binary output in Scala 5 6 Maps 5 7 Option types 5 8 Objects and Classes

More information

Functional Programming and Haskell

Functional Programming and Haskell Functional Programming and Haskell Tim Dawborn University of Sydney, Australia School of Information Technologies Tim Dawborn Functional Programming and Haskell 1/22 What are Programming Paradigms? A programming

More information

JVM ByteCode Interpreter

JVM ByteCode Interpreter JVM ByteCode Interpreter written in Haskell (In under 1000 Lines of Code) By Louis Jenkins Presentation Schedule ( 15 Minutes) Discuss and Run the Virtual Machine first

More information

A Brief Introduction to Scheme (I)

A Brief Introduction to Scheme (I) A Brief Introduction to Scheme (I) Philip W. L. Fong pwlfong@cs.uregina.ca Department of Computer Science University of Regina Regina, Saskatchewan, Canada Scheme Scheme I p.1/44 Scheme: Feature Set A

More information

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail. OOP in Java 1 Outline 1. Getting started, primitive data types and control structures 2. Classes and objects 3. Extending classes 4. Using some standard packages 5. OOP revisited Parts 1 to 3 introduce

More information

The current topic: Python. Announcements. Python. Python

The current topic: Python. Announcements. Python. Python The current topic: Python Announcements! Introduction! reasons for studying languages! language classifications! simple syntax specification Object-oriented programming: Python Types and values Syntax

More information

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

More information

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

PROGRAMMING IN HASKELL. Chapter 2 - First Steps PROGRAMMING IN HASKELL Chapter 2 - First Steps 0 Glasgow Haskell Compiler GHC is the leading implementation of Haskell, and comprises a compiler and interpreter; The interactive nature of the interpreter

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

UNIX Shell Programming

UNIX Shell Programming $!... 5:13 $$ and $!... 5:13.profile File... 7:4 /etc/bashrc... 10:13 /etc/profile... 10:12 /etc/profile File... 7:5 ~/.bash_login... 10:15 ~/.bash_logout... 10:18 ~/.bash_profile... 10:14 ~/.bashrc...

More information

LECTURE 16. Functional Programming

LECTURE 16. Functional Programming LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

More information

Organization of Programming Languages CS3200/5200N. Lecture 11

Organization of Programming Languages CS3200/5200N. Lecture 11 Organization of Programming Languages CS3200/5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Functional vs. Imperative The design of the imperative languages

More information

Functional Programming

Functional Programming Functional Programming CS331 Chapter 14 Functional Programming Original functional language is LISP LISt Processing The list is the fundamental data structure Developed by John McCarthy in the 60 s Used

More information

Answers to AWK problems. Shell-Programming. Future: Using loops to automate tasks. Download and Install: Python (Windows only.) R

Answers to AWK problems. Shell-Programming. Future: Using loops to automate tasks. Download and Install: Python (Windows only.) R Today s Class Answers to AWK problems Shell-Programming Using loops to automate tasks Future: Download and Install: Python (Windows only.) R Awk basics From the command line: $ awk '$1>20' filename Command

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming Java Syntax Program Structure Variables and basic data types. Industry standard naming conventions. Java syntax and coding conventions If Then Else Case statements Looping (for,

More information

Functional Programming Concepts for Data Processing

Functional Programming Concepts for Data Processing Functional Programming Concepts for Data Processing Chris Lindholm UCAR SEA 2018 1 / 70 About Me I work at CU LASP I work primarily with Scala I teach Haskell at work Goal: leverage FP to improve scientific

More information

Lecture 1 August 9, 2017

Lecture 1 August 9, 2017 Programming in Haskell S P Suresh http://www.cmi.ac.in/~spsuresh Lecture 1 August 9, 2017 Administrative Mondays and Wednesdays at 9.10 am at Lecture Hall 6 Evaluation: Quizzes, 4 5 programming assignments,

More information

Functions & First Class Function Values

Functions & First Class Function Values Functions & First Class Function Values PLAI 1st ed Chapter 4, PLAI 2ed Chapter 5 The concept of a function is itself very close to substitution, and to our with form. Consider the following morph 1 {

More information

CSE : Python Programming

CSE : Python Programming CSE 399-004: Python Programming Lecture 10: Functional programming, Memoization March 26, 2007 http://www.seas.upenn.edu/~cse39904/ Announcements Should have received email about meeting times Length:

More information

Functions, Closures and Control Abstraction

Functions, Closures and Control Abstraction Functions, Closures and Control Abstraction Christopher Simpkins csimpkin@spsu.edu CS 3693, Fall 2011 Chris Simpkins (Georgia Tech) CS 3693 Scala 2011-09-07 1 / 1 Aside: drop and take (Optional) homework:

More information

Haskell through HUGS THE BASICS

Haskell through HUGS THE BASICS Haskell through HUGS THE BASICS FP for DB Basic HUGS 1 Algorithmic Imperative Languages variables assignment if condition then action1 else action2 loop block while condition do action repeat action until

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

More information

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi Shell / Python Tutorial CS279 Autumn 2017 Rishi Bedi Shell (== console, == terminal, == command prompt) You might also hear it called bash, which is the most widely used shell program macos Windows 10+

More information

More Lambda Calculus and Intro to Type Systems

More Lambda Calculus and Intro to Type Systems #1 More Lambda Calculus and Intro to Type Systems #2 Plan Heavy Class Participation Thus, wake up! (not actually kidding) Lambda Calculus How is it related to real life? Encodings Fixed points Type Systems

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

An introduction to functional programming. July 23, 2010

An introduction to functional programming. July 23, 2010 An introduction to functional programming July 23, 2010 About Outline About About What is functional programming? What is? Why functional programming? Why? is novel. is powerful. is fun. About A brief

More information

Cunning Plan. One-Slide Summary. Functional Programming. Functional Programming. Introduction to COOL #1. Classroom Object-Oriented Language

Cunning Plan. One-Slide Summary. Functional Programming. Functional Programming. Introduction to COOL #1. Classroom Object-Oriented Language Functional Programming Introduction to COOL #1 Cunning Plan Functional Programming Types Pattern Matching Higher-Order Functions Classroom Object-Oriented Language Methods Attributes Inheritance Method

More information

Shell. SSE2034: System Software Experiment 3, Fall 2018, Jinkyu Jeong

Shell. SSE2034: System Software Experiment 3, Fall 2018, Jinkyu Jeong Shell Prof. Jinkyu Jeong (Jinkyu@skku.edu) TA -- Minwoo Ahn (minwoo.ahn@csl.skku.edu) TA -- Donghyun Kim (donghyun.kim@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2016 Lecture 4a Andrew Tolmach Portland State University 1994-2016 Pragmatics of Large Values Real machines are very efficient at handling word-size chunks of data (e.g.

More information

CSCI-GA Final Exam

CSCI-GA Final Exam CSCI-GA 2110-003 - Final Exam Instructor: Thomas Wies Name: Sample Solution ID: You have 110 minutes time. There are 7 assignments and you can reach 110 points in total. You can solve the exercises directly

More information

Assignment 2. Summary. Some Important bash Instructions. CSci132 Practical UNIX and Programming Assignment 2, Fall Prof.

Assignment 2. Summary. Some Important bash Instructions. CSci132 Practical UNIX and Programming Assignment 2, Fall Prof. Assignment 2 Summary The purpose of this assignment is to give you some practice in bash scripting. When you write a bash script, you are really writing a program in the bash programming language. In class

More information

INF 102 CONCEPTS OF PROG. LANGS FUNCTIONAL COMPOSITION. Instructors: James Jones Copyright Instructors.

INF 102 CONCEPTS OF PROG. LANGS FUNCTIONAL COMPOSITION. Instructors: James Jones Copyright Instructors. INF 102 CONCEPTS OF PROG. LANGS FUNCTIONAL COMPOSITION Instructors: James Jones Copyright Instructors. Topics Recursion Higher-order functions Continuation-Passing Style Monads (take 1) Identity Monad

More information

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors.

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors. INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION Instructors: Crista Lopes Copyright Instructors. Topics Recursion Higher-order functions Continuation-Passing Style Monads (take 1) Identity Monad Maybe

More information

python 01 September 16, 2016

python 01 September 16, 2016 python 01 September 16, 2016 1 Introduction to Python adapted from Steve Phelps lectures - (http://sphelps.net) 2 Python is interpreted Python is an interpreted language (Java and C are not). In [1]: 7

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Values and Types We divide the universe of values according to types A type is a set of values and

More information

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators 1 Professor: Sana Odeh odeh@courant.nyu.edu Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators Review What s wrong with this line of code? print( He said Hello ) What s wrong with

More information

Computational Expression

Computational Expression Computational Expression Variables, Primitive Data Types, Expressions Janyl Jumadinova 28-30 January, 2019 Janyl Jumadinova Computational Expression 28-30 January, 2019 1 / 17 Variables Variable is a name

More information

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia CPL 2016, week 10 Clojure functional core Oleg Batrashev Institute of Computer Science, Tartu, Estonia April 11, 2016 Overview Today Clojure language core Next weeks Immutable data structures Clojure simple

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Type Inference Some statically typed languages, like ML (and to a lesser extent Scala), offer alternative

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

SKILL AREA 304: Review Programming Language Concept. Computer Programming (YPG)

SKILL AREA 304: Review Programming Language Concept. Computer Programming (YPG) SKILL AREA 304: Review Programming Language Concept Computer Programming (YPG) 304.1 Demonstrate an Understanding of Basic of Programming Language 304.1.1 Explain the purpose of computer program 304.1.2

More information

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example Overview Elements of Programming Languages Lecture 11: Object-oriented functional programming James Cheney University of Edinburgh October 30, 2017 We ve now covered: basics of functional programming (with

More information

CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages CS 314 Principles of Programming Languages Lecture 15: Review and Functional Programming Zheng (Eddy) Zhang Rutgers University March 19, 2018 Class Information Midterm exam forum open in Sakai. HW4 and

More information