Workshop: Towards Highly Portable Software Jakarta, 21 – 23 January 2003 Diselenggarakan oleh Universitas IndonesiaUniversitas Indonesia Part 1 : Programming.

Slides:



Advertisements
Similar presentations
CS3012: Formal Languages and Compilers Static Analysis the last of the analysis phases of compilation type checking - is an operator applied to an incompatible.
Advertisements

Introduction to Compilation of Functional Languages Wanhe Zhang Computing and Software Department McMaster University 16 th, March, 2004.
Introduction to Recursion and Recursive Algorithms
Kathleen Fisher cs242 Reading: “A history of Haskell: Being lazy with class”,A history of Haskell: Being lazy with class Section 6.4 and Section 7 “Monads.
Lecture # 21 Chapter 6 Uptill 6.4. Type System A type system is a collection of rules for assigning type expressions to the various parts of the program.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Functional Programming Universitatea Politehnica Bucuresti Adina Magda Florea
Grab Bag of Interesting Stuff. Topics Higher kinded types Files and handles IOError Arrays.
A Lightning Tour of Haskell Lecture 1, Designing and Using Combinators John Hughes.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Advanced Programming Handout 12 Higher-Order Types (SOE Chapter 18)
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Cse536 Functional Programming 1 6/23/2015 Lecture #17, Dec. 1, 2004 Todays Topics – Higher Order types »Type constructors that take types as arguments.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Chapter 5 Polymorphic and Higher-Order Functions.
Cse536 Functional Programming 1 7/14/2015 Lecture #2, Sept 29, 2004 Reading Assignments –Begin Chapter 2 of the Text Home work #1 can be found on the webpage,
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 19: Functions, Types and Data Structures in Haskell COMP 144 Programming Language.
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
1 COMP313A Functional Programming (1). 2 Main Differences with Imperative Languages Say more about what is computed as opposed to how Pure functional.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Advanced Functional Programming 2009 Ulf Norell (lecture by Jean-Philippe Bernardy)
Chapter 9: Functional Programming in a Typed Language.
COP4020 Programming Languages Functional Programming Prof. Xin Yuan.
1 Functional Programming Lecture 6 - Algebraic Data Types.
Overview of the Haskell 98 Programming Language
0 Functors in Haskell Adapted from material by Miran Lipovaca.
© M. Winter COSC 4P41 – Functional Programming Programming with actions Why is I/O an issue? I/O is a kind of side-effect. Example: Suppose there.
CS5205Haskell1 CS5205: Foundations in Programming Languages FP with Haskell A pure lazy functional language that embodies many innovative ideas in language.
COMP313A Functional Programming (1)
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
1 Haskell Kevin Atkinson John Simmons. 2 Contents Introduction Type System Variables Functions Module System I/O Conclusions.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Interactive Programs: I/O and Monads Dr. Hyunyoung Lee.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
Advanced Functional Programming Tim Sheard 1 Lecture 17 Advanced Functional Programming Tim Sheard Oregon Graduate Institute of Science & Technology Lecture:
Workshop: Towards Highly Portable Software Jakarta, 21 – 23 January 2003 Diselenggarakan oleh Universitas IndonesiaUniversitas Indonesia Part 1 : Programming.
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
0 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Odds and Ends,
Workshop: Towards Highly Portable Software Jakarta, 21 – 23 January 2003 Diselenggarakan oleh Universitas IndonesiaUniversitas Indonesia Part 1 : Transformation.
1 Objective Caml (Ocaml) Aaron Bloomfield CS 415 Fall 2005.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
Chapter 1: Preliminaries Lecture # 2. Chapter 1: Preliminaries Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation.
24-Jun-16 Haskell Dealing with impurity. Purity Haskell is a “pure” functional programming language Functions have no side effects Input/output is a side.
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
Functional Programming Lecture 1 - Introduction Professor Muffy Calder.
© M. Winter COSC 4P41 – Functional Programming Some functions id :: a -> a id x = x const :: a -> b -> a const k _ = k ($) :: (a -> b) -> a -> b.
Advanced Functional Programming 2010
CS314 – Section 5 Recitation 9
Functional Programming
Functional Programming
Principles of programming languages 12: Functional programming
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
ML: a quasi-functional language with strong typing
A lightening tour in 45 minutes
Haskell.
CSE 3302 Programming Languages
Haskell Dealing with impurity 30-Nov-18.
FP Foundations, Scheme In Text: Chapter 14.
PROGRAMMING IN HASKELL
Advanced Functional Programming
Haskell Types, Classes, and Functions, Currying, and Polymorphism
Haskell Dealing with impurity 8-Apr-19.
Grab Bag of Interesting Stuff
Programming Languages
Haskell Dealing with impurity 29-May-19.
PROGRAMMING IN HASKELL
Haskell Dealing with impurity 28-Jun-19.
Presentation transcript:

Workshop: Towards Highly Portable Software Jakarta, 21 – 23 January 2003 Diselenggarakan oleh Universitas IndonesiaUniversitas Indonesia Part 1 : Programming and Abstraction Dr. Ir. I.S.W.B. A. Azurat Lecture 1: Functional Programming

2 Content Functional programming style –Syntax –Types –Tree recursion –Laziness –Circularity Practice FP is a big subject... we will only take the highlights.

3 Problem Computing salary It's not difficult So, why do we pay lots of money to automate it !?

4 Programming Programming: –Algorithmic aspect: how to solve a problem –Communication aspect: tell the computer how to do it Algorithm  intertesting Communication  annoying! (especially talking to something that only chat in 0 and 1...) Lots of language-specific detail which has nothing to do with the actual problem.

5 Programming Communication with a computer is a big problem.... Precision is needed  formal communication with programming language. Formalism constrains communication, making it difficult  production cost. Communication in general is a big problem... Multiply errors: communication errors.

6 Abstraction Real world is too complex... our mind precieve only an abstraction of it. Abstract: not real... Blindness is power!

7 Thesis 1: Abstraction The key towards low cost software is to teach the compiler, not the programmer.

8 Functional Programming Use function as an abstract concept of what a program is. What do we 'abstract' away? –Pointers –Garbage collection –In-situ array –I/O Very suitable for program transformation Why not Java?? –Use the right tool to do the right thing

9 Functional Programming Languages LISP, Scheme, Miranda, ML, Clean, Haskell Variations: –Strongly typed, untyped –Lazy, Strict –Pure, impure We're using Haskell Site: Sophisticated compilers and other tools avaialble for free! For education, check out Helium:

10 Example del :: Int -> [Int] -> [Int] del x [ ] = [ ] del x (y:s) | x==y = del x y | otherwise = y : del x y

11 You can also do it with less abstraction... void del0 (*int t) {if (null t) {return()} else if (t->item == 0) {*int s = t ; t = t->next free(s) ; del0(t) ; return() ; } else {del0(t->next); return(); } } Error rate, and thus production and maintenance cost increases with the ammount of 'dirty' code you have to write.

12 Types Basic types: Bool, Int, Char Tuple :(Int,Int) List: [Bool], [Int] Function: Bool -> Int Type variable a,b,c,... Polymorphic type [a] Self defined type More sophisticated: –Record –IO –Array

13 Polymorphism del :: Int -> [Int] -> [Int] del x [ ] = [ ] del x (y:s) | x==y = del x y | otherwise = y : del x y a -> [a] -> [a]

14 Higher Order Function Traditionally, a program is used to process data. data  program  data Why not pass program to as data? data  program  data program 

15 Higher Order Function filter :: (a->Bool) -> [a] -> [a] filter p [ ]= [ ] filter p (x:s) | p x= x : filter p s | otherwise= filter p s

16 Higher Order Function del x s = filter p s where p y = x/=y search :: String -> String -> [String] search w txt = filter p (words txt) where p z = isPrefixOf w z

17 Higher Order Function map :: (a->b) -> [a] -> [b] map f [ ]= [ ] map f (x : s)= f x : map f s capitalize :: String -> String capitalize s = map toUpper s

18 Partial Parametrization map :: (a -> b) -> [a] -> [b] (a -> b) -> ( [a] -> [b] ) capitalize s = map toUpper s Example, recall: map toUpper map toLower. map toUpper

19 Abstraction query :: [Employee] -> [Transaction] -> [Transaction] query es ts = (concat. map find. filter isManager) es where find employee = filter p ts where p transaction = #id transaction == #id employee Given a database of employee and a database of transactions, make a query to produce a list of all transactions made by all managers.

20 Syntax Sugar What's the point of being ellegant!? Express things naturally (intuitively) is as little words as possible. Haskel syntax sugars: –priority and associativity –infix and sufix coercion –sectioning –list comprehension –many more....

21 Priority and Associativity Write x + y * zrather thanx + (y * z) x : y : s rather than x : (y : s) Priority : see Prelude.hs Associativity: left, right, non-assoc

22 Coercion and Sectioning Infix coercion: f `map` s instead of map f s Prefix coercion: (+) x y instead of x + y Sectioning: (++ t) means (\s-> s ++ t) (t ++) means (\u-> t ++ u)

23 List Comprehension Example: [x + 1 | x 0] Combo of map and filter query :: [Employee] -> [Transaction] -> [Transaction] query es ts = (concat. map find. filter isManager) es where... query es ts = concat [find e | e <- es, isManager e]

24 Introducing New Types Type abbreviation: type PersonDB = [Person] data-type definition: data Color = Red | Green | Blue With parameter: data Maybe a = Nothing | Just a

25 Recursive Data Type data List a = Empty | Cons a (List a) length :: List a -> Int length Empty= 0 length (Cons x s)= 1 + length s

26 Representing Tree data Btree a = Node a (Btree a) (Btree a) | Leaf a Example: Node 10 (Leaf 0) (Leaf 20)

27 Tree Recursion data Btree a = Node a (Btree a) (Btree a) | Leaf a minT :: Btree a -> a minT (Leaf x)= x minT (Node x t u)= x `min` minT t `min` minT u

28 Tree Recursion replace :: a -> Btree a -> Btreea replace x (Leaf _ )= Leaf x replace x (Node _ t u)= Node x t' u' where t' = replace x t u' = replace x u repmin t = replace (minT t) t

29 Debugging with the Type Checker Exploit your type checker to debug your programs... Example: use Data Week = Monday | Tuesday |... Type checker will reject this: if day - 1 < - 1 then...

30 Debugging with the Type Checker Representing Red/Blue tree: With Btree: Node Blue (Leaf Red) (Leaf Red) Not all Btree is a Red/Blue tree You'll have to implement the check yourself...

31 Mutual Recursion odd0 = False odd(n+1)= even n even0= True even(n+1)= odd n data RedRootTree RedNode BlueRootTree BlueRootTree | RedLeaf data BlueRootTree BlueNode RedRootTree RedRootTree | BlueLeaf

32 Laziness... Consider this definition: True || b= True a || True= True a || b= False What happen if we evaluate this? (x>0) || find (==x) [0.. ]

33 Laziness Laziness intelligently breaks recursion: find :: (a->Bool) -> [a] -> Bool find p [ ]= False find p (x : s)= p x || find p s Often lead to more ellegant solutions: fillSpaceRight n s = take n (s ++ repeat ' ')

34 Lazily Walking a Tree... repmin: Replace all elements in a tree with its minimum. We did it in sequence: compute minimum first, then do replacement. We explicitly program this sequence. repmin t = replace (minT t) t

35 Lazily Walking a Tree... repmin t = u where (u, m) = foldT t m foldT (Leaf x) m = (Leaf m, x) foldT (Node x t u) m = (Node m t' u', z) where z= x `min` mt `min` mu (t', mt) = foldT t m (u', mu) = foldT u m Lazy evaluation will discover the correct order of 'attributes' computation

36 Classes Overloading: using the same name for different 'meaning' True == False 1 == 1 [1,2,3] == [ ] Class in Haskell: Eq a where (==) :: a -> a -> Bool (/=) :: a -> a -> Bool x /= y = not (x == y)

37 Instances instance Eq Bool where True == True = True False == False = True _ == _ = False instance Eq a => Eq [a] where [ ] == [ ] = True (x:s) == (y:t) = (x==y) && s==t _ == _ = False Examples:

38 Use del :: a -> [a] -> [a] del x [ ] = [ ] del x (y:s) | x==y = del x y | otherwise = y : del x y Eq a => a -> [a] -> [a]

39 I/O IO is in principle non-functional In Haskell IO actions are actracted by the type IO a A value of this type is an IO action that produces a value of type a Contains in principle no information regarding what kind of IO action it is.

40 Some basic IO functions putStr:: String -> IO( ) getChr:: IO Char getLine:: IO String readFile:: FilePath -> IO String writeFile:: FilePath -> String -> IO( )

41 Sequencing IO actions displayCountFile :: FilePath -> IO() displayCountFile fname = do { content <- readFile fname ; n <- return (length (words content)) ; putStr (show n) }

42 Manipulating IO An IO a value is a value like a any other Haskell value. You can manipulate it at will... Example: sequence (map displayCountFile fileList)

43 Some Haskell Syntax Rules Case sensitive Name of concrete type, data constructor, type constrytor begin with UPPER case character Name of function, variable, type variable begin with lower case character Haskell use strict identation rule...

44 Type error Be prepared to get depressed by Haskell's type error Haskell type checker/inference is very powerful. Type messaging system is somewhat less developed. Improvement in on the way... e.g. the new type checker by B. Heeren (used in Helium)