120 likes | 293 Views
Functional Programming. Theoretical foundation Church’s - calculus expressions and evaluation rules Characteristics Single assignment variables (pure FP) Recursion Rule-based and pattern matching (ML, Haskell, F#) High-order functions Lazy evaluation (Haskell)
E N D
Functional Programming • Theoretical foundation • Church’s -calculus • expressions and evaluation rules • Characteristics • Single assignment variables (pure FP) • Recursion • Rule-based and pattern matching (ML, Haskell, F#) • High-order functions • Lazy evaluation (Haskell) • Meta-programming (Scheme) by Neng-Fa Zhou
F# • A hybrid language • ML-like functional programming • Iimperative programming • OOP • Scripting • Runs on the .NET platform • It is possible to use any .NET library from F# • It is possible to use F# library from other .NET languages such as C# • Available for free • Works with Visual Studio • Standalone fsharp interpreter fsi by Neng-Fa Zhou
F# vs. Prolog • Common characteristics • Repetition via recursion • High-order • Garbage collection • Differences • Strongly typed vs. dynamically typed • Functional vs. relational • Prolog supports unification and backtracking by Neng-Fa Zhou
Types • int -- 123, -10 • float -- 122.123, 0.23e-10 • bool -- true, false • char -- ‘a’ • string -- “abc” • list -- [1;2;3], 1::[2;3], [1]@[2;3] • array -- [|1;2;3|] • tuple -- ("abc",1,true) • union -- type MyBool = | True | False by Neng-Fa Zhou
Operators • +, -, *, /, % • &&, ||,not • =, <>, <, >, <=, >= by Neng-Fa Zhou
let • let x = 1+2+3 • let f x y = x+y • let f (x,y) = x+y • let rec f n = if n = 0 then 1 else n*(f n-1) by Neng-Fa Zhou
Pattern Matching let rec len lst = match lst with | [] -> 0 | _::lst1 -> 1+len lst1 by Neng-Fa Zhou
Tail Recursion let rec len1 ac lst = match lst with | [] -> ac | (_::lstr) -> len1 (ac+1) lstr let len lst = len1 0 lst by Neng-Fa Zhou
Unions type SExp = | O | S of Sexp let rec sum x y = match x with | O -> y | S x1 -> S(sum x1 y) by Neng-Fa Zhou
Unions (Cont.) type TreeInt = | Void | Leaf of int | Node of int*TreeInt*TreeInt let rec count tree = match tree with | Void -> 0 | Leaf(_) -> 1 | Node(_,left,right) -> 1+ (count left) + (count right) by Neng-Fa Zhou
High-order Functions let succ = fun x -> x+1 List.map succ [1;2;3] List.map (fun x -> x+1) [1;2;3] by Neng-Fa Zhou
map and fold let rec map f lst = match lst with | [] -> [] | (car :: cdr) -> (f car)::(map f cdr) let rec fold f lst acc = match lst with | [] -> acc | (car :: cdr) -> f car (fold f cdr acc) let rec foldl f lst acc = match lst with | [] -> acc | (car :: cdr) -> foldl f cdr (f car acc) by Neng-Fa Zhou