A Quick introduction to F#

Size: px
Start display at page:

Download "A Quick introduction to F#"

Transcription

1 A Quick introduction to F# and my take on why functional programming matters Juhana Helovuo Atostek Oy

2 Contents Atostek F# Why should I care, elaborated Easier to reason about Performance Safety Summary This presentation uses materials from Visual Studio Help, Wikipedia, Github, and other parts of the Internet. May contain unnatural colours, artificial examples, and traces of nuts.

3 Atostek Oy Since 1999, office in Hermia AAA credit rating Owned by personnel Head count ~ 50 - Mostly M.Sc. or Dr.Tech. from TUT + students Mil. 4,5 4 3,5 3 2,5 2 1,5 1 0, Atostek Expertising your project

4 Atostek Aatos - Tueksi hankintoihin 4

5 F#

6 F# : General properties The functional language for Microsoft s.net platform Strict evaluation Direct support for.net OO features multi-paradigm Manipulating standard.net objects causes side effects F# standard library can be used for pure computation Standard component of Visual Studio since VS 2008 Developed mostly from ML (Milner et al., 1973) Also influence from OCaml, Python(!), Haskell, Scala, Erlang Native on.net Runs on Common Language Runtime, the.net virtual machine Compiled to Common Intermediate Language ( = CLR assembly) Basic data types implemented on Common Type System Many parts compatible with C#: strings, numbers, method calls, generics But e.g. Lists and Maps and other default libraries are different

7 Basic F# expressions > let x = * 4 ;; val x : int = 14 > type Person = { name : string ; age : int } ;; > let aa = { name = "Aatos" ; age = 3 } ;; val aa : Person = {name = "Aatos"; age = 3;} > [1..3] ;; val it : int list = [1; 2; 3] > seq { for i in 0.. x do if i % 2 = 0 then yield i+2 } ;; val it : seq<int> = seq [2; 4; 6; 8;...] > if aa.age >= 18 then printfn "Yes" else printfn "No ;; No val it : unit = () alternatively: printfn < if aa.age >= 18 then "Yes" else "No" ;; > ['a'.. 'f'] > List.map int val it : int list = [97; 98; 99; 100; 101; 102]

8 Common library types: List, Seq, Map, Option List< a> is Lisp-style linked list. Seq< a> Lazy but non-memoizing sequence Implemented using generators Many data structures can convert themselves to Seq Is really IEnumerable<a> from.net in disguise Map< Key, Value> is an ordered indexable collection (balanced tree). type Option< a> = Some of a None Can be used to add null value to a type. Safe, since contents can be only accessed after pattern match

9 Operations on whole data structures F# Seq.map Seq.map2 Seq.fold Seq.foldBack Seq.filter Seq.scan... List.map List.filter... Map.map Map.filter... Haskell map (fmap) zipwith foldr foldl filter scan concat any all... Atostek Oy

10 Functions and pattern matching type Expression = Number of int Add of Expression * Expression Multiply of Expression * Expression Variable of string let rec Evaluate (env:map<string,int>) exp = match exp with Number n -> n Add (x, y) -> Evaluate env x + Evaluate env y Multiply (x, y) -> Evaluate env x * Evaluate env y Variable id -> env.[id] let environment = Map.ofList [ "a", 1 ; "b", 2 ; "c", 3 ] // Create an expression tree that represents the expression: a + 2 * b. let expressiontree1 = Add(Variable "a", Multiply(Number 2, Variable "b")) // Evaluate the expression a + 2 * b, given the // table of values for the variables. let result = Evaluate environment expressiontree1

11 Computation Expressions Code blocks where computation semantics can be defined (within limits) Similar to do-notation is Haskell, but more syntactic constructs Examples: State (monad) Option (Maybe, monad) Step-by-step computation Undo-computation Async Query expressions (LINQ) Seq expressions Software Transactional Memory (STM)

12 Computation expression: state type State<'a, 's> = State of ('s -> 'a * 's) let counterworkflow = let runstate (State s) a = s a let getstate = State (fun s -> (s,s)) let putstate s = State (fun _ -> ((),s)) type StateBuilder() = member this.return(a) = State (fun s -> (a,s)) member this.bind(m,k) = State (fun s -> let (a,s') = runstate m s runstate (k a) s') member this.returnfrom (m) = m let s = state { do! DoSomething let! a = Foobar do! WithA a return a+1 } runstate s 0 stateful pure let state = new StateBuilder()

13 Computation expression: state static member GetYYYAndXXX : State<XXXState, XRetTypeX> = state { let s = System.XXX() let ll = XXX let! cc = XXXState.getXXX let! m = XXXState.getMMM } [... ] // TODO: so far there are no XXX other XX than YYY let e = mm.geteee > Seq.map (function Choice1Of2 both -> A both Choice2Of2 only -> B only) > Seq.groupBy (fun t -> t.xxxs) > Seq.map (fun (c,ts) -> Set.map ll.getxxx c > Seq.map (fun g -> g,list.ofseq ts ) ) > Seq.concat > Map.ofSeqWith (@) [... ] return { c = ccc; m = allmmm }

14 Computation expression: async open System.Net open Microsoft.FSharp.Control.WebExtensions // List<(string*string)> let urllist = [ "Microsoft.com", " "MSDN", " "Bing", " ] let fetchasync(name, url:string) = async { try let uri = new System.Uri(url) let webclient = new WebClient() let! html = webclient.asyncdownloadstring(uri) printfn "Read %d characters for %s" html.length name with ex -> printfn "%s" (ex.message); } let runall() = urllist > Seq.map fetchasync > Async.Parallel > Async.RunSynchronously > ignore runall()

15 Short F# summary ML-derived language on.net Can be used for everything that C# can be, except for null reference exceptions. Recursion is the goto: In practical programming, all iteration is done using library functions. Actual recursion is hardly ever used. Computation expressions allow defining new behavior But with a fixed syntax

16 Why should I care, longer explanation. About functional programming in general, we are going outside F# here

17 Example: Insertion sort 1 2 key key Sorted Unsorted One of the simplest sorting algorithms Page 3 in Introduction to Algorithms

18 Shorter or easier to reason about? Example: insertion sort -- Functional Language -- Haskell, but F# translation would -- only have slightly different syntax insertionsort :: Ord a => [a] -> [a] insertionsort [] = [] insertionsort (x:xs) = insert x (insertionsort xs) where insert :: Ord a => a -> [a] -> [a] insert x [] = [x] insert x (y:ys) x < y = x : y : ys otherwise = y : insert x ys -- 8 lines of code lines of (compiler-inferrable) types -- Generic Imperative Language -- Object-oriented or not -- Input is array A[1..n]. j = 1 while j < n do i j j j + 1 key A[j] while i > 0 and A[i] > key do A[i + 1] A[i] i i-1 endwhile A[i + 1] key endwhile -- Output is array A[1..n], now sorted lines code -- Not much longer!

19 Proving Imperative insertion sort j = 1 while j < n do i j j j + 1 key A[j] while i > 0 and A[i] > key do A[i + 1] A[i] i i-1 endwhile A[i + 1] key endwhile 1 2 Input and output are the array A[1..n] Correctness: 1. The output is sorted SortedA(1,n) i ϵ [1,n-1] : A[i] A[i+1] 2. The output has the same elements as the input. p : A out = Permutation(p,A in ) 3. The algorithm terminates. Requirements 1 and 2 are most interesting and difficult, so we ll try those. We ll handle 2 rather informally due to space, time, and boringness constraints. Requirement 3 is left for homework for those who are interested. Note that i,j,k: SortedA(i,j) ^ SortedA(j,k) SortedA(i,k) i: SortedA (i,i) key Sorted key

20 Proving Imperative insertion sort { n 1 } j = 1 { j = 1 ^ I ^ P } while j < n do { I ^ j < n ^ P} i j { I ^ j < n ^ i=j ^ P } j j + 1 { I Sorted(1,j-1) ^ i=j-1 ^ 1<j n ^ P } key A[j] { Sorted(1,j-1) ^ i=j-1 ^ 1<j n ^ key=a[j] ^ P } { I2 } while i > 0 and A[i] > key do { I2 ^ i>0 ^ A[i]>key } A[i + 1] A[i] { SortedA(1,j) ^ A[i+1..j] key ^ i>0 ^ A[i]>key ^ A[i+1] = A[i] } i i-1 { SortedA(1,j) ^ A[i+2..j] key ^ i 0 ^ A[i+1]>key ^ A[i+2] = A[i+1] } {I2} endwhile { I2 ^ (i 0 v A[i] key) but P } { I } A[i + 1] key { I ^ P } endwhile { I ^ j n ^ P} { SortedA(1,n) ^ P } 1 2 key Sorted key We use P to denote that A is still a permutation of the input. Outer loop invariant I: SortedA(1,j) ^ 1 j n Inner loop invariant I2: SortedA(1,j-1) ^ (i=j-1 v A[j-1] A[j]) ^ A[i+1..j] key ^ i 0 Where A[i+1..j] key means k ϵ [i+1..j] : A[k] key

21 Proving Imperative insertion sort { n 1 } j = 1 { j = 1 ^ I ^ P } while j < n do { I ^ j < n ^ P} i j { I ^ j < n ^ i=j ^ P } j j + 1 { I Sorted(1,j-1) ^ i=j-1 ^ 1<j n ^ P } key A[j] { Sorted(1,j-1) ^ i=j-1 ^ 1<j n ^ key=a[j] ^ P } { I2 } while i > 0 and A[i] > key do { I2 ^ i>0 ^ A[i]>key } A[i + 1] A[i] { SortedA(1,j) ^ A[i+1..j] key ^ i>0 ^ A[i]>key ^ A[i+1] = A[i] } i i-1 { SortedA(1,j) ^ A[i+2..j] key ^ i 0 ^ A[i+1]>key ^ A[i+2] = A[i+1] } {I2} endwhile { I2 ^ (i 0 v A[i] key) but P } { I } A[i + 1] key { I ^ P } endwhile { I ^ j n ^ P} { SortedA(1,n) ^ P } 1 2 key Sorted key I: SortedA(1,j) ^ 1 j n I2: SortedA(1,j-1) ^ ( i=j-1 v A[j-1] A[j] ) ^ A[i+1..j] key ^ i 0 Case A[j-1] A[j]: SortedA(1,j-1) SortedA(1,j) Case i=j-1: A[i]=A[i+1] A[j-1] A[j] SortedA(1,j) A[i] > key ^ A[i+1]=A[i] A[i+1] key A[i+1..j] key

22 Proving Imperative insertion sort { n 1 } j = 1 { j = 1 ^ I ^ P } while j < n do { I ^ j < n ^ P} i j { I ^ j < n ^ i=j ^ P } j j + 1 { I Sorted(1,j-1) ^ i=j-1 ^ 1<j n ^ P } key A[j] { Sorted(1,j-1) ^ i=j-1 ^ 1<j n ^ key=a[j] ^ P } { I2 } while i > 0 and A[i] > key do { I2 ^ i>0 ^ A[i]>key } A[i + 1] A[i] { SortedA(1,j) ^ A[i+1..j] key ^ i>0 ^ A[i]>key ^ A[i+1] = A[i] } i i-1 { SortedA(1,j) ^ A[i+2..j] key ^ i 0 ^ A[i+1]>key ^ A[i+2] = A[i+1] } {I2} endwhile { I2 ^ (i 0 v A[i] key) but P } { I } A[i + 1] key { I ^ P } endwhile { I ^ j n ^ P} { SortedA(1,n) ^ P } 1 2 key Sorted key I: SortedA(1,j) ^ 1 j n I2: SortedA(1,j-1) ^ ( i=j-1 v A[j-1] A[j] ) ^ A[i+1..j] key ^ i 0 Case A[j-1] A[j] : SortedA(1,j-1) SortedA(1,j) Case i=j-1 ^ i 0 : i 0 i=0 j=1 SortedA(1,j) Case i=j-1 ^ A[i] key : A[i+1..i+1] key A[i] key A[i+1] A[j-1] key A[j] SortedA(1,j)

23 Proving Imperative insertion sort { n 1 } j = 1 { j = 1 ^ I ^ P } while j < n do { I ^ j < n ^ P} i j { I ^ j < n ^ i=j ^ P } j j + 1 { I Sorted(1,j-1) ^ i=j-1 ^ 1<j n ^ P } key A[j] { Sorted(1,j-1) ^ i=j-1 ^ 1<j n ^ key=a[j] ^ P } { I2 } while i > 0 and A[i] > key do { I2 ^ i>0 ^ A[i]>key } A[i + 1] A[i] { SortedA(1,j) ^ A[i+1..j] key ^ i>0 ^ A[i]>key ^ A[i+1] = A[i] } i i-1 { SortedA(1,j) ^ A[i+2..j] key ^ i 0 ^ A[i+1]>key ^ A[i+2] = A[i+1] } {I2} endwhile { I2 ^ (i 0 v A[i] key) but P } { I } A[i + 1] key { I ^ P } endwhile { I ^ j n ^ P} { SortedA(1,n) ^ P } 1 2 key Sorted key I: SortedA(1,j) ^ 1 j n I2: SortedA(1,j-1) ^ ( i=j-1 v A[j-1] A[j] ) ^ A[i+1..j] key ^ i 0 Assignment A[i + 1] key maintains I, because - SortedA(1,j) - A[i] key - A[i+1..j] key P is restored, because too long to show. Appeal to picture above. Also would need to show that all indexing of A is within [1..n]. TL;DR.

24 Proving functional insertion sort 1 insertionsort [] = [] 2 insertionsort (x:xs) = 3 insert x (insertionsort xs) 4 where 5 insert x [] = [x] 6 insert x (y:ys) 7 x < y = x : y : ys 8 otherwise = y : insert x ys Define Sorted(x) list x is sorted in ascending order Req1: a : Sorted(insertionSort a) Req2: p : insertionsort a = Perm(p,a) Req3: Termination. Show Req1 using induction over length(a): Base: length a = 0: Trivially true by line 1. IHypo: length a = k Sorted(insertionSort a) IStep: If length a = k+1, then insertionsort a = insertionsort (x:xs) = insert x (insertionsort xs). Now insertionsort xs is sorted by induction hypothesis. We need to show: Sorted(L) Sorted(insert x L) And we are done.

25 Proving functional insertion sort 1 insertionsort [] = [] 2 insertionsort (x:xs) = 3 insert x (insertionsort xs) 4 where 5 insert x [] = [x] 6 insert x (y:ys) 7 x < y = x : y : ys 8 otherwise = y : insert x ys Show Sorted(L) Sorted(insert x L) : Assume Sorted(L) and use induction on length of L. Base: length L = 0 : Line 5 Trivially sorted. IHypo: length L = k and Sorted(L) Sorted(insert x L) IStep: If length L = k+1, then insert x L = insert x (y:ys) and we have 2 cases: case x<y: result is x:y:ys Sorted([x,y]) ^ Sorted(y:ys) Sorted(x:y:xs). case x y: result is y : insert x ys Sorted(insert x ys) by IHypo. y x ^ y (all of ys), because Sorted(L) Sorted(y : insert x ys) And we are done.

26 Proving functional insertion sort 1 insertionsort [] = [] 2 insertionsort (x:xs) = 3 insert x (insertionsort xs) 4 where 5 insert x [] = [x] 6 insert x (y:ys) 7 x < y = x : y : ys 8 otherwise = y : insert x ys Req2: p : insertionsort a = Perm(p,a) The value of insert is a permutation of the input values (by case analysis of code). Same holds for insertionsort. Done. [Strictly speaking, the above is circular reasoning because of the recursion in the code, and therefore the logic is not valid. To get this formally right, use again induction along the length of input to avoid circular argument.] Req3: Termination (Time complexity!) insert L runs in O(length L), because each recursion step makes input 1 element shorter and is O(1). insertionsort L similarly, each step takes O(n), therefore complexity is O((length L) 2 ) and therefore finite.

27 Easier to reason about? Functional We can apply deduction rules to expressions and use substitution principle referential transparency The logical formulas are valid or not without reference to program counter Recursive control induction proof Imperative We can (must) analyze program state between statements. Analysis must follow control flow and use deduction rules for each control structure Need to invent(!) invariants This technique is known as Hoare Logic Course MAT or e.g. Wikipedia.

28 Faster Functional Parallel Programing in Corento

29 Corento A single-assignment data flow language for computation kernels Designed and implemented at Atostek with Nokia Corento routines are called from C (or equivalent) Not independent programs Matrix*Vector multiplication code shown here inline function vecmulscal {value len:integer} (v1: [Float # len], x: Float) : [Float # len] = for a in v1 do value all a*x end end -- Golub & VanLoan: -- Matrix Computations 3rd ed. pp. 6, -- Algorithm (Column Gaxpy) inline function matmulvec {value rows:integer, value cols:integer} (a:[[float # rows] # cols], xs:[float # cols]) : [Float # rows] = let init_sum = veczero{rows}(); in for ac in a, x in xs initially cumsum = init_sum; do yc = vecmulscal{rows}(ac,x); next cumsum = vecadd{rows}(cumsum,yc); value last cumsum end end end Atostek Oy

30 Matrix * Matrix in portable C void c_matmul_gaxpy(int rowsa, int colsa, int colsb, float* a, float* b, float* result) { int rowsb = colsa; int rowa,cola,colb; } for (colb=0;colb<colsb;colb++) { cola=0; for (rowa=0;rowa<rowsa;rowa++) { result[colb*rowsa+rowa] = a[cola*rowsa+rowa]*b[colb*rowsb+cola]; } for (cola=1;cola<colsa;cola++) { for (rowa=0;rowa<rowsa;rowa++) { result[colb*rowsa+rowa] += a[cola*rowsa+rowa]*b[colb*rowsb+cola]; } } } Atostek Oy

31 void cv_matmul_gaxpy(int rowsa, int colsa, int colsb, float* a, float *b, float* result) { float32x4_t* va = (float32x4_t *) a; float32x4_t* vb = (float32x4_t *) b; float32x4_t* resultv = (float32x4_t *) result; } // clear output float32x4_t* tmp = (float32x4_t *) result; const float32x4_t zerov = {0.0,0.0,0.0,0.0}; int i; for (i=0; i<colsa*colsb/4; ++i) { *tmp++ = zerov; } // to support vectorization, perform calculation in 4x4 blockwise int rowblocks = rowsa/4; int colblocks = colsb/4; int colblocks2 = colblocks*colblocks; int rowblock,colblock,ablock; for (rowblock=0; rowblock<rowblocks; ++rowblock) { for (colblock=0; colblock<colblocks; ++colblock) { for (ablock=0; ablock<colblocks; ++ablock) { float32x4_t a0 = *(va+rowblock+0*colblocks+4*rowblocks*ablock); float32x4_t a1 = *(va+rowblock+1*colblocks+4*rowblocks*ablock); float32x4_t a2 = *(va+rowblock+2*colblocks+4*rowblocks*ablock); float32x4_t a3 = *(va+rowblock+3*colblocks+4*rowblocks*ablock); float32x4_t b0 = *(vb+4*colblock*rowblocks+0*rowblocks+ablock); float32x4_t b1 = *(vb+4*colblock*rowblocks+1*rowblocks+ablock); float32x4_t b2 = *(vb+4*colblock*rowblocks+2*rowblocks+ablock); float32x4_t b3 = *(vb+4*colblock*rowblocks+3*rowblocks+ablock); float32x4_t* blockptr = resultv+4*colblock*rowblocks+rowblock; //float32x4_t* blockptr = bptr; // col 0 //float32x4_t oval0 = *(resultv+(0+(4*colblock))*rowblocks+rowblock); float32x4_t oval0 = *blockptr; float32x4_t b00 = vdupq_n_f32(vgetq_lane_f32(b0,0)); float32x4_t c0a = vmlaq_f32(oval0, a0, b00); float32x4_t b10 = vdupq_n_f32(vgetq_lane_f32(b0,1)); float32x4_t c0b = vmlaq_f32(c0a, a1, b10); float32x4_t b20 = vdupq_n_f32(vgetq_lane_f32(b0,2)); float32x4_t c0c = vmlaq_f32(c0b, a2, b20); float32x4_t b30 = vdupq_n_f32(vgetq_lane_f32(b0,3)); //*(resultv+(1+(4*colblock))*rowblocks+rowblock) = vmlaq_f32(c1c, a3, b31); *blockptr = vmlaq_f32(c0c, a3, b30); blockptr += rowblocks; // col 1 // float32x4_t oval1 = *(resultv+(1+(4*colblock))*rowblocks+rowblock); float32x4_t oval1 = *blockptr; float32x4_t b01 = vdupq_n_f32(vgetq_lane_f32(b1,0)); float32x4_t c1a = vmlaq_f32(oval1, a0, b01); float32x4_t b11 = vdupq_n_f32(vgetq_lane_f32(b1,1)); float32x4_t c1b = vmlaq_f32(c1a, a1, b11); float32x4_t b21 = vdupq_n_f32(vgetq_lane_f32(b1,2)); float32x4_t c1c = vmlaq_f32(c1b, a2, b21); float32x4_t b31 = vdupq_n_f32(vgetq_lane_f32(b1,3)); *blockptr = vmlaq_f32(c1c, a3, b31); blockptr += rowblocks; //*(resultv+(1+(4*colblock))*rowblocks+rowblock) = vmlaq_f32(c1c, a3, b31); // col 2 //float32x4_t oval2 = *(resultv+(2+(4*colblock))*rowblocks+rowblock); float32x4_t oval2 = *blockptr; float32x4_t b02 = vdupq_n_f32(vgetq_lane_f32(b2,0)); float32x4_t c2a = vmlaq_f32(oval2, a0, b02); float32x4_t b12 = vdupq_n_f32(vgetq_lane_f32(b2,1)); float32x4_t c2b = vmlaq_f32(c2a, a1, b12); float32x4_t b22 = vdupq_n_f32(vgetq_lane_f32(b2,2)); float32x4_t c2c = vmlaq_f32(c2b, a2, b22); float32x4_t b32 = vdupq_n_f32(vgetq_lane_f32(b2,3)); *blockptr = vmlaq_f32(c2c, a3, b32); blockptr += rowblocks; //*(resultv+(2+(4*colblock))*rowblocks+rowblock) = vmlaq_f32(c2c, a3, b32); // col 3 //float32x4_t oval3 = *(resultv+(3+(4*colblock))*rowblocks+rowblock); float32x4_t oval3 = *blockptr; float32x4_t b03 = vdupq_n_f32(vgetq_lane_f32(b3,0)); float32x4_t c3a = vmlaq_f32(oval3, a0, b03); float32x4_t b13 = vdupq_n_f32(vgetq_lane_f32(b3,1)); float32x4_t c3b = vmlaq_f32(c3a, a1, b13); float32x4_t b23 = vdupq_n_f32(vgetq_lane_f32(b3,2)); float32x4_t c3c = vmlaq_f32(c3b, a2, b23); float32x4_t b33 = vdupq_n_f32(vgetq_lane_f32(b3,3)); *blockptr = vmlaq_f32(c3c, a3, b33); } } } SIMD optimized Matrix multiplication C code for ARM Up to 7x faster than portable C code Cortex-A8, 32x32 matrix Works only on ARM with Neon SIMD unit Clearly more difficult to write, understand, and debug However, embedded DSP codes cannot afford 7x performance loss must use SIMD when available... float32x4_t oval3 = *blockptr; float32x4_t b03 = vdupq_n_f32(vgetq_lane_f32(b3,0)); float32x4_t c3a = vmlaq_f32(oval3, a0, b03); float32x4_t b13 = vdupq_n_f32(vgetq_lane_f32(b3,1)); float32x4_t c3b = vmlaq_f32(c3a, a1, b13);... Atostek Oy

32 void cv_matmul_gaxpy(int rowsa, int colsa, int colsb, float* a, float *b, float* result) { vector float* va = (vector float *) a; vector float* vb = (vector float *) b; vector float* resultv = (vector float *) result; // clear output vector float* tmp = (vector float *) result; const vector float zerov = {0.0,0.0,0.0,0.0}; int i; for (i=0; i<colsa*colsb/16; ++i) { *tmp++ = zerov; *tmp++ = zerov; *tmp++ = zerov; *tmp++ = zerov; } // to support vectorization, perform calculation in 4x4 blockwise int rowblocks = rowsa/4; int colblocks = colsb/4; int colblocks2 = colblocks*colblocks; int rowblock,colblock,ablock; for (rowblock=0; rowblock<rowblocks; ++rowblock) { for (colblock=0; colblock<colblocks; ++colblock) { //vector float* bptr = resultv+4*colblock*rowblocks+rowblock; for (ablock=0; ablock<colblocks; ++ablock) { vector float a0 = *(va+rowblock+0*colblocks+4*rowblocks*ablock); vector float a1 = *(va+rowblock+1*colblocks+4*rowblocks*ablock); vector float a2 = *(va+rowblock+2*colblocks+4*rowblocks*ablock); vector float a3 = *(va+rowblock+3*colblocks+4*rowblocks*ablock); vector float b0 = *(vb+4*colblock*rowblocks+0*rowblocks+ablock); vector float b1 = *(vb+4*colblock*rowblocks+1*rowblocks+ablock); vector float b2 = *(vb+4*colblock*rowblocks+2*rowblocks+ablock); vector float b3 = *(vb+4*colblock*rowblocks+3*rowblocks+ablock); vector float* blockptr = resultv+4*colblock*rowblocks+rowblock; //vector float* blockptr = bptr; // col 0 //vector float oval0 = *(resultv+(0+(4*colblock))*rowblocks+rowblock); vector float oval0 = *blockptr; vector float b00 = spu_splats(spu_extract(b0,0)); vector float c0a = spu_madd(a0, b00, oval0); vector float b10 = spu_splats(spu_extract(b0,1)); vector float c0b = spu_madd(a1, b10, c0a); vector float b20 = spu_splats(spu_extract(b0,2)); vector float c0c = spu_madd(a2, b20, c0b); vector float b30 = spu_splats(spu_extract(b0,3)); //*(resultv+(1+(4*colblock))*rowblocks+rowblock) = spu_madd(a3, b31, c1c); *blockptr = spu_madd(a3, b30, c0c); blockptr += rowblocks; Same for Cell SPU ~12x faster than portable C Works only on Cell SPU We would like to avoid coding like this For each platform // col 1 // vector float oval1 = *(resultv+(1+(4*colblock))*rowblocks+rowblock); vector float oval1 = *blockptr; vector float b01 = spu_splats(spu_extract(b1,0)); vector float c1a = spu_madd(a0, b01, oval1); vector float b11 = spu_splats(spu_extract(b1,1)); vector float c1b = spu_madd(a1, b11, c1a); vector float b21 = spu_splats(spu_extract(b1,2)); vector float c1c = spu_madd(a2, b21, c1b); vector float b31 = spu_splats(spu_extract(b1,3)); *blockptr = spu_madd(a3, b31, c1c); blockptr += rowblocks; //*(resultv+(1+(4*colblock))*rowblocks+rowblock) = spu_madd(a3, b31, c1c); } // col 2 //vector float oval2 = *(resultv+(2+(4*colblock))*rowblocks+rowblock); vector float oval2 = *blockptr; vector float b02 = spu_splats(spu_extract(b2,0)); vector float c2a = spu_madd(a0, b02, oval2); vector float b12 = spu_splats(spu_extract(b2,1)); vector float c2b = spu_madd(a1, b12, c2a); vector float b22 = spu_splats(spu_extract(b2,2)); vector float c2c = spu_madd(a2, b22, c2b); vector float b32 = spu_splats(spu_extract(b2,3)); *blockptr = spu_madd(a3, b32, c2c); blockptr += rowblocks; //*(resultv+(2+(4*colblock))*rowblocks+rowblock) = spu_madd(a3, b32, c2c); // col 3 //vector float oval3 = *(resultv+(3+(4*colblock))*rowblocks+rowblock); vector float oval3 = *blockptr; vector float b03 = spu_splats(spu_extract(b3,0)); vector float c3a = spu_madd(a0, b03, oval3); vector float b13 = spu_splats(spu_extract(b3,1)); vector float c3b = spu_madd(a1, b13, c3a); vector float b23 = spu_splats(spu_extract(b3,2)); vector float c3c = spu_madd(a2, b23, c3b); vector float b33 = spu_splats(spu_extract(b3,3)); *blockptr = spu_madd(a3, b33, c3c); } } // blockptr += rowblocks; //*(resultv+(3+(4*colblock))*rowblocks+rowblock) = spu_madd(a3, b33, c3c);... vector float oval3 = *blockptr; vector float b03 = spu_splats(spu_extract(b3,0)); vector float c3a = spu_madd(a0, b03, oval3); vector float b13 = spu_splats(spu_extract(b3,1)); vector float c3b = spu_madd(a1, b13, c3a);... Atostek Oy

33 Timing results on ARM Cortex-A8 Mul tests the matrix multiplication code fragments shown on previous slides Corento beats even C+SIMD code - mostly because LLVM instruction scheduler is better than GCC 4.2 and Cortex-A8 is sensitive to that. Atostek Oy

34 Safer FP vs. IEC 61508

35 More safety, less bugs IEC and ISO (and others) are standards for developing systems with Safety Functions Safety Function failure can cause loss of life and limb Standards give guidelines for software development for different Safety Integrity Levels Conforming to standard (esp. at higher SILs this is a lot of work) Requires a lot of documentation, verification, and testing Functional programming to the rescue

36 Examples of recommended/required measures from safety standards Technique/measure Functional programming, e.g. Haskell or F# Use of language subsets Enforcement of strong typing Enforcement of low complexity (e.g. in a function) Not many dangerous features (compared to C++/asm) and those are usually easy to spot. Unavoidable Easy Use of style guides - Use of naming conventions Restricted coupling between software components One entry and one exit point in subprograms (functions) No dynamic objects or online test during creation Initialization of variables Avoid global variables (or justify usage) Limited use of pointers No hidden data flow or control flow As in other languages, except when naming convention is substitute for typing easier Functional interfaces There is no complicated interaction of control and data flow. Automatic memory management Unavoidable Very easy Very easy Easy

37 Summary F# is ML-derived functional language on.net Backed by Microsoft Functional programming advantages Understandable: easier to reason about Code design Bug hunting Automated code transformations (compiler optimization) (Verification) Faster: better optimizable, parallelizable Optimization is mandatory to get reasonable performance Safer: simpler semantics, easier to analyze behavior Practical safety: Less bugs and failures Theoretical safety: Proving properties more feasible Bureucratic safety: Passes audits

38 Homework: Extend the diagram below to cover F#.

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

Testing. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 2. [Faculty of Science Information and Computing Sciences]

Testing. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 2. [Faculty of Science Information and Computing Sciences] Testing Advanced functional programming - Lecture 2 Wouter Swierstra and Alejandro Serrano 1 Program Correctness 2 Testing and correctness When is a program correct? 3 Testing and correctness When is a

More information

Algorithms. Notations/pseudo-codes vs programs Algorithms for simple problems Analysis of algorithms

Algorithms. Notations/pseudo-codes vs programs Algorithms for simple problems Analysis of algorithms Algorithms Notations/pseudo-codes vs programs Algorithms for simple problems Analysis of algorithms Is it correct? Loop invariants Is it good? Efficiency Is there a better algorithm? Lower bounds * DISC

More information

CITS 3242 Programming Paradigms Part II. Topic 10: Imperative Programming

CITS 3242 Programming Paradigms Part II. Topic 10: Imperative Programming CITS 3242 Programming Paradigms Part II Topic 10: Imperative Programming This topic covers the background and motivations for imperative programming, as well as the imperative constructs in F# - reference

More information

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University Functional Languages CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Historical Origins 2 The imperative and functional models grew out of work

More information

Optimising Functional Programming Languages. Max Bolingbroke, Cambridge University CPRG Lectures 2010

Optimising Functional Programming Languages. Max Bolingbroke, Cambridge University CPRG Lectures 2010 Optimising Functional Programming Languages Max Bolingbroke, Cambridge University CPRG Lectures 2010 Objectives Explore optimisation of functional programming languages using the framework of equational

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

Introduction to OCaml

Introduction to OCaml Fall 2018 Introduction to OCaml Yu Zhang Course web site: http://staff.ustc.edu.cn/~yuzhang/tpl References Learn X in Y Minutes Ocaml Real World OCaml Cornell CS 3110 Spring 2018 Data Structures and Functional

More information

Programovací jazyky F# a OCaml. Chapter 6. Sequence expressions and computation expressions (aka monads)

Programovací jazyky F# a OCaml. Chapter 6. Sequence expressions and computation expressions (aka monads) Programovací jazyky F# a OCaml Chapter 6. Sequence expressions and computation expressions (aka monads) Sequence expressions 1. (generating sequences) Sequence expressions» Lazily generated sequences of

More information

Chapter 11 :: Functional Languages

Chapter 11 :: Functional Languages Chapter 11 :: Functional Languages Programming Language Pragmatics Michael L. Scott Copyright 2016 Elsevier 1 Chapter11_Functional_Languages_4e - Tue November 21, 2017 Historical Origins The imperative

More information

Introduction to Functional Programming and Haskell. Aden Seaman

Introduction to Functional Programming and Haskell. Aden Seaman Introduction to Functional Programming and Haskell Aden Seaman Functional Programming Functional Programming First Class Functions Expressions (No Assignment) (Ideally) No Side Effects Different Approach

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

Lectures 20, 21: Axiomatic Semantics

Lectures 20, 21: Axiomatic Semantics Lectures 20, 21: Axiomatic Semantics Polyvios Pratikakis Computer Science Department, University of Crete Type Systems and Static Analysis Based on slides by George Necula Pratikakis (CSD) Axiomatic Semantics

More information

The Haskell HOP: Higher-order Programming

The Haskell HOP: Higher-order Programming The Haskell HOP: Higher-order Programming COS 441 Slides 6 Slide content credits: Ranjit Jhala, UCSD Agenda Haskell so far: First-order functions This time: Higher-order functions: Functions as data, arguments

More information

Compiler Optimization Techniques

Compiler Optimization Techniques Compiler Optimization Techniques Department of Computer Science, Faculty of ICT February 5, 2014 Introduction Code optimisations usually involve the replacement (transformation) of code from one sequence

More information

Introduction. chapter Functions

Introduction. chapter Functions chapter 1 Introduction In this chapter we set the stage for the rest of the book. We start by reviewing the notion of a function, then introduce the concept of functional programming, summarise the main

More information

CS 242. Fundamentals. Reading: See last slide

CS 242. Fundamentals. Reading: See last slide CS 242 Fundamentals Reading: See last slide Syntax and Semantics of Programs Syntax The symbols used to write a program Semantics The actions that occur when a program is executed Programming language

More information

Programming with Math and Logic

Programming with Math and Logic .. Programming with Math and Logic an invitation to functional programming Ed Morehouse Wesleyan University The Plan why fp? terms types interfaces The What and Why of Functional Programming Computing

More information

INTRODUCTION TO HASKELL

INTRODUCTION TO HASKELL INTRODUCTION TO HASKELL PRINCIPLES OF PROGRAMMING LANGUAGES Norbert Zeh Winter 2018 Dalhousie University 1/81 HASKELL: A PURELY FUNCTIONAL PROGRAMMING LANGUAGE Functions are first-class values: Can be

More information

Continuation Passing Style. Continuation Passing Style

Continuation Passing Style. Continuation Passing Style 161 162 Agenda functional programming recap problem: regular expression matcher continuation passing style (CPS) movie regular expression matcher based on CPS correctness proof, verification change of

More information

Introduction to Functional Programming

Introduction to Functional Programming PART I TE RI AL Introduction to Functional Programming MA CHAPTER 1: A Look at Functional Programming History CO PY RI GH TE D CHAPTER 2: Putting Functional Programming into a Modern Context 1A Look at

More information

Stop coding Pascal. Saturday, April 6, 13

Stop coding Pascal. Saturday, April 6, 13 Stop coding Pascal...emotional sketch about past, present and future of programming languages, Python, compilers, developers, Life, Universe and Everything Alexey Kachayev CTO at KitApps Inc. Open source

More information

Outline. Introduction Concepts and terminology The case for static typing. Implementing a static type system Basic typing relations Adding context

Outline. Introduction Concepts and terminology The case for static typing. Implementing a static type system Basic typing relations Adding context Types 1 / 15 Outline Introduction Concepts and terminology The case for static typing Implementing a static type system Basic typing relations Adding context 2 / 15 Types and type errors Type: a set of

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

Example Algorithms. CSE 2320 Algorithms and Data Structures Alexandra Stefan. University of Texas at Arlington. Last updated 9/7/2016

Example Algorithms. CSE 2320 Algorithms and Data Structures Alexandra Stefan. University of Texas at Arlington. Last updated 9/7/2016 Example Algorithms CSE 2320 Algorithms and Data Structures Alexandra Stefan University of Texas at Arlington Last updated 9/7/2016 1 Summary Binary Search See the notation conventions (e.g. log 2 N = lg

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Type Systems, Names and Binding CMSC 330 - Spring 2013 1 Topics Covered Thus Far! Programming languages Ruby OCaml! Syntax specification Regular expressions

More information

Applicative, traversable, foldable

Applicative, traversable, foldable Applicative, traversable, foldable Advanced functional programming - Lecture 3 Wouter Swierstra 1 Beyond the monad So far, we have seen how monads define a common abstraction over many programming patterns.

More information

CITS 3242 Programming Paradigms

CITS 3242 Programming Paradigms CITS 3242 Programming Paradigms Topic 8: Generic functions, sequences, sets and maps This topic covers a number of useful features of F# and it s libraries sequences: generic functions, sequences, sets,

More information

COS 320. Compiling Techniques

COS 320. Compiling Techniques Topic 5: Types COS 320 Compiling Techniques Princeton University Spring 2016 Lennart Beringer 1 Types: potential benefits (I) 2 For programmers: help to eliminate common programming mistakes, particularly

More information

Principles of Programming Languages. Lecture Outline

Principles of Programming Languages. Lecture Outline Principles of Programming Languages CS 492 Lecture 1 Based on Notes by William Albritton 1 Lecture Outline Reasons for studying concepts of programming languages Programming domains Language evaluation

More information

Monads. Functional Programming (CS4011) Monads

Monads. Functional Programming (CS4011) Monads Monads Functional Programming (CS4011) Andrew Butterfield Glenn Strong Foundations & Methods Group, Discipline of Software Systems Trinity College, University of Dublin {Andrew.Butterfield,Glenn.Strong}@cs.tcd.ie

More information

Simply-Typed Lambda Calculus

Simply-Typed Lambda Calculus #1 Simply-Typed Lambda Calculus #2 Back to School What is operational semantics? When would you use contextual (small-step) semantics? What is denotational semantics? What is axiomatic semantics? What

More information

Reasoning About Imperative Programs. COS 441 Slides 10

Reasoning About Imperative Programs. COS 441 Slides 10 Reasoning About Imperative Programs COS 441 Slides 10 The last few weeks Agenda reasoning about functional programming It s very simple and very uniform: substitution of equal expressions for equal expressions

More information

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University

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

More information

Option Values, Arrays, Sequences, and Lazy Evaluation

Option Values, Arrays, Sequences, and Lazy Evaluation Option Values, Arrays, Sequences, and Lazy Evaluation Björn Lisper School of Innovation, Design, and Engineering Mälardalen University bjorn.lisper@mdh.se http://www.idt.mdh.se/ blr/ Option Values, Arrays,

More information

Introduction to the Lambda Calculus

Introduction to the Lambda Calculus Introduction to the Lambda Calculus Overview: What is Computability? Church s Thesis The Lambda Calculus Scope and lexical address The Church-Rosser Property Recursion References: Daniel P. Friedman et

More information

Quicksort (CLRS 7) We saw the divide-and-conquer technique at work resulting in Mergesort. Mergesort summary:

Quicksort (CLRS 7) We saw the divide-and-conquer technique at work resulting in Mergesort. Mergesort summary: Quicksort (CLRS 7) We saw the divide-and-conquer technique at work resulting in Mergesort. Mergesort summary: Partition n elements array A into two subarrays of n/2 elements each Sort the two subarrays

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

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming Closures Mooly Sagiv Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming Summary 1. Predictive Parsing 2. Large Step Operational Semantics (Natural) 3. Small Step Operational Semantics

More information

CS Lecture 6: Map and Fold. Prof. Clarkson Spring Today s music: Selections from the soundtrack to 2001: A Space Odyssey

CS Lecture 6: Map and Fold. Prof. Clarkson Spring Today s music: Selections from the soundtrack to 2001: A Space Odyssey CS 3110 Lecture 6: Map and Fold Prof. Clarkson Spring 2015 Today s music: Selections from the soundtrack to 2001: A Space Odyssey Review Course so far: Syntax and semantics of (most of) OCaml Today: No

More information

Applicative, traversable, foldable

Applicative, traversable, foldable Applicative, traversable, foldable Advanced functional programming - Lecture 4 Wouter Swierstra and Alejandro Serrano 1 Beyond the monad So far, we have seen how monads define a common abstraction over

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

Functional Programming The Meta Language (ML) and Functional Programming Daniel S. Fava danielsf@ifi.uio.no Department of informatics University of Oslo, Norway Motivation ML Demo Which programming languages are functional?

More information

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine.

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine. 1. true / false By a compiler we mean a program that translates to code that will run natively on some machine. 2. true / false ML can be compiled. 3. true / false FORTRAN can reasonably be considered

More information

Static Program Analysis Part 1 the TIP language

Static Program Analysis Part 1 the TIP language Static Program Analysis Part 1 the TIP language http://cs.au.dk/~amoeller/spa/ Anders Møller & Michael I. Schwartzbach Computer Science, Aarhus University Questions about programs Does the program terminate

More information

A general introduction to Functional Programming using Haskell

A general introduction to Functional Programming using Haskell A general introduction to Functional Programming using Haskell Matteo Rossi Dipartimento di Elettronica e Informazione Politecnico di Milano rossi@elet.polimi.it 1 Functional programming in a nutshell

More information

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d) CMSC 330: Organization of Programming Languages Tail Calls A tail call is a function call that is the last thing a function does before it returns let add x y = x + y let f z = add z z (* tail call *)

More information

The story so far. Elements of Programming Languages. While-programs. Mutable vs. immutable

The story so far. Elements of Programming Languages. While-programs. Mutable vs. immutable The story so far Elements of Programming Languages Lecture 12: Imperative programming James Cheney University of Edinburgh November 4, 2016 So far we ve mostly considered pure computations. Once a variable

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

CMSC 330: Organization of Programming Languages. Functional Programming with OCaml

CMSC 330: Organization of Programming Languages. Functional Programming with OCaml CMSC 330: Organization of Programming Languages Functional Programming with OCaml 1 What is a functional language? A functional language: defines computations as mathematical functions discourages use

More information

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited CMSC 330: Organization of Programming Languages Type Systems, Names & Binding Topics Covered Thus Far Programming languages Syntax specification Regular expressions Context free grammars Implementation

More information

Lecture 5 Sorting Arrays

Lecture 5 Sorting Arrays Lecture 5 Sorting Arrays 15-122: Principles of Imperative Computation (Spring 2018) Frank Pfenning, Rob Simmons We begin this lecture by discussing how to compare running times of functions in an abstract,

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

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Topics Covered Thus Far CMSC 330: Organization of Programming Languages Topics Covered Thus Far CMSC 330: Organization of Programming Languages Names & Binding, Type Systems Programming languages Ruby Ocaml Lambda calculus Syntax specification Regular expressions Context free

More information

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1 A Second Look At ML Chapter Seven Modern Programming Languages, 2nd ed. 1 Outline Patterns Local variable definitions A sorting example Chapter Seven Modern Programming Languages, 2nd ed. 2 Two Patterns

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

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without previous written authorization. 1 2 The simplest way to create

More information

Haskell & functional programming, some slightly more advanced stuff. Matteo Pradella

Haskell & functional programming, some slightly more advanced stuff. Matteo Pradella Haskell & functional programming, some slightly more advanced stuff Matteo Pradella pradella@elet.polimi.it IEIIT, Consiglio Nazionale delle Ricerche & DEI, Politecnico di Milano PhD course @ UniMi - Feb

More information

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions PROGRAMMING IN HASKELL CS-205 - Chapter 6 - Recursive Functions 0 Introduction As we have seen, many functions can naturally be defined in terms of other functions. factorial :: Int Int factorial n product

More information

Foundations. Yu Zhang. Acknowledgement: modified from Stanford CS242

Foundations. Yu Zhang. Acknowledgement: modified from Stanford CS242 Spring 2013 Foundations Yu Zhang Acknowledgement: modified from Stanford CS242 https://courseware.stanford.edu/pg/courses/317431/ Course web site: http://staff.ustc.edu.cn/~yuzhang/fpl Reading Concepts

More information

Mutation. COS 326 David Walker Princeton University

Mutation. COS 326 David Walker Princeton University Mutation COS 326 David Walker Princeton University Mutation? 2 Thus far We have considered the (almost) purely functional subset of Ocaml. We ve had a few side effects: printing & raising exceptions. Two

More information

CSCC24 Functional Programming Scheme Part 2

CSCC24 Functional Programming Scheme Part 2 CSCC24 Functional Programming Scheme Part 2 Carolyn MacLeod 1 winter 2012 1 Based on slides from Anya Tafliovich, and with many thanks to Gerald Penn and Prabhakar Ragde. 1 The Spirit of Lisp-like Languages

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

Types and Type Inference

Types and Type Inference Types and Type Inference Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on the course homepage Outline General discussion

More information

Type Checking and Type Inference

Type Checking and Type Inference Type Checking and Type Inference Principles of Programming Languages CSE 307 1 Types in Programming Languages 2 Static Type Checking 3 Polymorphic Type Inference Version: 1.8 17:20:56 2014/08/25 Compiled

More information

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules Haskell: From Basic to Advanced Part 2 Type Classes, Laziness, IO, Modules Qualified types In the types schemes we have seen, the type variables were universally quantified, e.g. ++ :: [a] -> [a] -> [a]

More information

Programming Languages, Summary CSC419; Odelia Schwartz

Programming Languages, Summary CSC419; Odelia Schwartz Programming Languages, Summary CSC419; Odelia Schwartz Chapter 1 Topics Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation Criteria Influences on Language Design

More information

PROBLEM SOLVING AND PYTHON PROGRAMMING

PROBLEM SOLVING AND PYTHON PROGRAMMING ALGORITHM UNIT-1 It is defined as a sequence of instructions that describe a method for solving a problem. In other words it is a step by step procedure for solving a problem. Properties of Algorithms

More information

Multi-paradigm Declarative Languages

Multi-paradigm Declarative Languages Michael Hanus (CAU Kiel) Multi-paradigm Declarative Languages ICLP 2007 1 Multi-paradigm Declarative Languages Michael Hanus Christian-Albrechts-University of Kiel Programming Languages and Compiler Construction

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 4 Thomas Wies New York University Review Last week Control Structures Selection Loops Adding Invariants Outline Subprograms Calling Sequences Parameter

More information

Verification of an ML compiler. Lecture 3: Closures, closure conversion and call optimisations

Verification of an ML compiler. Lecture 3: Closures, closure conversion and call optimisations Verification of an ML compiler Lecture 3: Closures, closure conversion and call optimisations Marktoberdorf Summer School MOD 2017 Magnus O. Myreen, Chalmers University of Technology Implementing the ML

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

CHENNAI MATHEMATICAL INSTITUTE M.Sc. / Ph.D. Programme in Computer Science

CHENNAI MATHEMATICAL INSTITUTE M.Sc. / Ph.D. Programme in Computer Science CHENNAI MATHEMATICAL INSTITUTE M.Sc. / Ph.D. Programme in Computer Science Entrance Examination, 5 May 23 This question paper has 4 printed sides. Part A has questions of 3 marks each. Part B has 7 questions

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

Foundations of Computation

Foundations of Computation The Australian National University Semester 2, 2018 Research School of Computer Science Tutorial 5 Dirk Pattinson Foundations of Computation The tutorial contains a number of exercises designed for the

More information

Lecture 5: Lazy Evaluation and Infinite Data Structures

Lecture 5: Lazy Evaluation and Infinite Data Structures Lecture 5: Lazy Evaluation and Infinite Data Structures Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense October 3, 2017 How does Haskell evaluate a

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

CS 161 Computer Security

CS 161 Computer Security Wagner Spring 2014 CS 161 Computer Security 1/27 Reasoning About Code Often functions make certain assumptions about their arguments, and it is the caller s responsibility to make sure those assumptions

More information

CSE341, Fall 2011, Midterm Examination October 31, 2011

CSE341, Fall 2011, Midterm Examination October 31, 2011 CSE341, Fall 2011, Midterm Examination October 31, 2011 Please do not turn the page until the bell rings. Rules: The exam is closed-book, closed-note, except for one side of one 8.5x11in piece of paper.

More information

Programming Languages Fall Prof. Liang Huang

Programming Languages Fall Prof. Liang Huang Programming Languages Fall 2014 Prof. Liang Huang huang@qc.cs.cuny.edu Computer Science is no more about computers than astronomy is about telescopes. (Mis)attributed to Edsger Dijkstra, 1970. Computer

More information

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors

More information

Chapter 13: Reference. Why reference Typing Evaluation Store Typings Safety Notes

Chapter 13: Reference. Why reference Typing Evaluation Store Typings Safety Notes Chapter 13: Reference Why reference Typing Evaluation Store Typings Safety Notes References Computational Effects Also known as side effects. A function or expression is said to have a side effect if,

More information

Programming Languages

Programming Languages Programming Languages Andrea Flexeder Chair for Theoretical Computer Science Prof. Seidl TU München winter term 2010/2011 Lecture 10 Side-Effects Main Points you should get: Why monads? What is a monad?

More information

Introduction to Haskell

Introduction to Haskell Introduction to Haskell Matt Mullins Texas A&M Computing Society October 6, 2009 Matt Mullins (TACS) Introduction to Haskell October 6, 2009 1 / 39 Outline Introduction to Haskell Functional Programming

More information

Unit #3: Recursion, Induction, and Loop Invariants

Unit #3: Recursion, Induction, and Loop Invariants Unit #3: Recursion, Induction, and Loop Invariants CPSC 221: Basic Algorithms and Data Structures Jan Manuch 2017S1: May June 2017 Unit Outline Thinking Recursively Recursion Examples Analyzing Recursion:

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

Types, Type Inference and Unification

Types, Type Inference and Unification Types, Type Inference and Unification Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Cornell CS 6110 Summary (Functional Programming) Lambda Calculus Basic ML Advanced ML: Modules, References,

More information

CS A331 Programming Language Concepts

CS A331 Programming Language Concepts CS A331 Programming Language Concepts Lecture 4 Programming Language Semantics and Code Generation February 3, 2014 Sam Siewert PLP Companion Materials CD-ROM is On-Line: http://booksite.elsevier.com/9780123745149/?isbn=978

More information

Programming Paradigms

Programming Paradigms PP 2017/18 Unit 18 Summary of Basic Concepts 1/13 Programming Paradigms Unit 18 Summary of Basic Concepts J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE PP 2017/18 Unit 18

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2016 Lecture 3a Andrew Tolmach Portland State University 1994-2016 Formal Semantics Goal: rigorous and unambiguous definition in terms of a wellunderstood formalism (e.g.

More information

Chapter 6 Control Flow. June 9, 2015

Chapter 6 Control Flow. June 9, 2015 Chapter 6 Control Flow June 9, 2015 Expression evaluation It s common in programming languages to use the idea of an expression, which might be a simple object function invocation over some number of arguments

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

Types and Type Inference

Types and Type Inference CS 242 2012 Types and Type Inference Notes modified from John Mitchell and Kathleen Fisher Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on Web!! Outline General discussion of

More information

Introduction to ML. Based on materials by Vitaly Shmatikov. General-purpose, non-c-like, non-oo language. Related languages: Haskell, Ocaml, F#,

Introduction to ML. Based on materials by Vitaly Shmatikov. General-purpose, non-c-like, non-oo language. Related languages: Haskell, Ocaml, F#, Introduction to ML Based on materials by Vitaly Shmatikov slide 1 ML General-purpose, non-c-like, non-oo language Related languages: Haskell, Ocaml, F#, Combination of Lisp and Algol-like features (1958)

More information

Lectures Basics in Procedural Programming: Machinery

Lectures Basics in Procedural Programming: Machinery Lectures 3-4-5-6 Basics in Procedural Programming: Machinery February 21-28, 2014 2014-03-01 11:04:07 1/48 Lecture3-6E-2014.pdf (#21) Basics in Procedural Programming: Machinery Naming and Binding Mutable

More information

Scope and Introduction to Functional Languages. Review and Finish Scoping. Announcements. Assignment 3 due Thu at 11:55pm. Website has SML resources

Scope and Introduction to Functional Languages. Review and Finish Scoping. Announcements. Assignment 3 due Thu at 11:55pm. Website has SML resources Scope and Introduction to Functional Languages Prof. Evan Chang Meeting 7, CSCI 3155, Fall 2009 Announcements Assignment 3 due Thu at 11:55pm Submit in pairs Website has SML resources Text: Harper, Programming

More information

Computation Club: Gödel s theorem

Computation Club: Gödel s theorem Computation Club: Gödel s theorem The big picture mathematicians do a lot of reasoning and write a lot of proofs formal systems try to capture the ideas of reasoning and proof in a purely mechanical set

More information

Sorting is a problem for which we can prove a non-trivial lower bound.

Sorting is a problem for which we can prove a non-trivial lower bound. Sorting The sorting problem is defined as follows: Sorting: Given a list a with n elements possessing a total order, return a list with the same elements in non-decreasing order. Remember that total order

More information

Software System Design and Implementation

Software System Design and Implementation Software System Design and Implementation Property-based Testing Gabriele Keller The University of New South Wales School of Computer Science and Engineering Sydney, Australia COMP3141 17s1 Testing in

More information

CS Lecture 6: Map and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey

CS Lecture 6: Map and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey CS 3110 Lecture 6: Map and Fold Prof. Clarkson Fall 2014 Today s music: Selections from the soundtrack to 2001: A Space Odyssey Review Features so far: variables, operators, let expressions, if expressions,

More information