Almost There. Attempt Two on Purity

Almost There. Attempt Two on Purity

Functional Paradigm Attempt One: Almost There. intint binsearch binsearch((intint a[],a[], int int start, start, int int end, end, int int val) val) { { if if (start (start >= >= end) end) return return -1; -1; if if (a[start] (a[start] == == val) val) return return start; start; if if (a[end] (a[end] == == val) val) return return end; end; How do we avoid this int mid = (start + end) / 2; int mid = (start + end) / 2; assignment? if if (val (val < < a[mid]) a[mid]) return return binsearchbinsearch(a,(a, start, start, mid,mid, val); val); return return binsearch binsearch(a,(a, mid, mid, end end -- 1,1, val); val); Rupesh Nasre. }} intint main main()() { { intint a[] a[] == {3,{3, 3, 3, 7, 7, 9, 9, 12, 12, 14, 14, 19, 19, 20, 20, 21,21, 27, 27, 41, 41, 53}; 53}; intint val val = = 41; 41; intint na na = = sizeof sizeof(a)(a) / /sizeof sizeof(*a);(*a); CS3100 Paradigms of Programming printf(“%d\n”,printf(“%d\n”, binsearch binsearch(a,(a, 0, 0, na, na, val)); val)); IIT Madras returnreturn 0; 0; Jul 2014 }} 4 Let's BinarySearch Attempt Two ● Implement a binsearch function in C to search intint binsearch binsearch((intint a[], a[], int int start, start, int int midmid, ,int int end, end, int int val) val) { { if if (start (start >= >= end) end) return return -1; -1; for an element in an input array. if if (a[start] (a[start] == == val)val) return return start; start; if if (a[end] (a[end] == == val) val) return return end; end; ● Constraint: Don't use = operator in binsearch. if if (val (val < < a[mid]) a[mid]) returnreturn binsearch binsearch(a,(a, start, start, (start (start + + mid) mid) / /2 2, , mid,mid, val); val); Use the trick again. intint binsearch binsearch(...)(...) { { return return binsearch binsearch(a,(a, mid, mid, (mid (mid + + end) end) / /2 2, ,end, end, val); val); ... } No assignments in ... } binsearch now. }} intint main main()() { { intint main main()() { { intint a[] a[] == {3, {3, 3, 3, 7, 7, 9, 9, 12, 12, 14, 14, 19, 19, 20, 20, 21, 21, 27,27, 41, 41, 53}; 53}; intint a[] a[] = = {3, {3, 3, 3, 7, 7, 9,9, 12, 12, 14,14, 19, 19, 20, 20, 21, 21, 27, 27, 41,41, 53}; 53}; intint val val = = 41; 41; intint val val = = 41; 41; intint na na = = sizeof sizeof(a)(a) / /sizeof sizeof(*a);(*a); Returns index of the printf(“%d\n”,printf(“%d\n”, binsearch binsearch(a,(a, val)); val)); element if present, -1 printf(“%d\n”,printf(“%d\n”, binsearch binsearch(a,(a, 0, 0, na na / /2 2, ,na, na, val)); val)); otherwise. returnreturn 0; 0; returnreturn 0; 0; }} }} 2 5 Let's BinarySearch On Purity ● How can we avoid assignment? ● Functional programs where side-effects are – Apply your tricks. disallowed are Pure Functional Programs. ● We can use parameter passing to simulate ● Most languages today are impure – but they assignment. support writing PFP. – Use function arguments and return values. ● Functional programs are value-based, not location-based. Therefore, most of them do not support explicit deallocation. – giving a name to a value versus storing a value into a memory location. ● For the same input, the output of a PFP is the 3 same. 6 But Assignments are Necessary! Syntax ● For what? ● (print “Hello World”) – Reuse. – Then, re-compute the value, don't assign. But these multiple xx == f(y);f(y); evaluations must ifif (x(x << 10)10) {{ ifif (f(y)(f(y) << 10)10) {{ be costly. g(x);g(x); g(f(y));g(f(y)); } else { }} else else {{ } else { ● Then don't evaluate h(xh(x ++ 1);1); h(f(y)h(f(y) + + 1);1); them – yet. }} }} ● Use memoisation. 7 10 Lisp Once we have a common language... ● (+ 2 3) ● McCarthy 1958. ● (if (= 1 1) 2 3) ● List Processing language. ● (if (= 1 2) 2 3) ● “the most intelligent way to misuse a computer” ● (list 1 2 3 4 5) ● There are multiple dialects of Lisp today. ● – I use clisp (ANSI Common Lisp Standard). (car '(1 2 3 4 5)) – OO, functional, general-purpose. ● (cdr '(1 2 3 4 5)) – Open source, available on Linux / Mac / Windows. ● (cons 1 '(2 3 4 5)) – For assignments, let's ask TAs. ● (cons '(1) '(2 3 4 5)) ● Lost In Stupid Parentheses 8 (append '(2 3) '(4 5 6)) Lots of Irritating Superfluous Parentheses11 Syntax But how do I come out? [23]> quit rupesh@pace$ clisp *** - SYSTEM::READ-EVAL-PRINT: variable QUIT has no value The following restarts are available: ... USE-VALUE :R1 Input a value to be used instead of QUIT. STORE-VALUE :R2 Input a new value for QUIT. [1]> hello Commands can be interpreted. ABORT :R3 Abort main loop Break 1 [24]> exit *** - SYSTEM::READ-EVAL-PRINT: variable HELLO has no value The following restarts are available: *** - SYSTEM::READ-EVAL-PRINT: variable EXIT has no value USE-VALUE :R1 Input a value to be used instead of HELLO. cAse-iNsenSitiVE The following restarts are available: STORE-VALUE :R2 Input a new value for HELLO. USE-VALUE :R1 Input a value to be used instead of EXIT. ABORT :R3 Abort debug loop STORE-VALUE :R2 Input a new value for EXIT. ABORT :R4 Abort debug loop ABORT :R3 Abort debug loop ABORT :R5 Abort debug loop ABORT :R4 Abort main loop ABORT :R6 Abort debug loop Break 2 [25]> Ctrl-C ABORT :R7 Abort debug loop *** - Ctrl-C: User break ABORT :R8 Abort main loop The following restarts are available: Break 1 [2]> (hello) Doesn't help. Considers it as a command. ABORT :R1 Abort debug loop [3]> 'hello Boss, this is not a command, this is data. ABORT :R2 Abort debug loop ABORT :R3 Abort main loop HELLO 9 Break 3 [26]> (quit) (exit) and Ctrl-D also work. 12 [4]> rupesh@pace$ Assignments List Manipulation ● Setq {var value}* Three primitives and one constant ● – (setq x (+ 3 2 1) y (cons x nil)) Available globally. get head of list: car ● get rest of list: cdr ● Let binding ● add an element to a list: cons – (let ((x 10) (y 20)) (+ x y)) Available locally. ● null list: nil or () – (let ((x 10) (y x)) (+ x y)) Error: Parallel assignment – (let* ((x 10) (y x)) (+ x y)) Okay: Sequential assignment Add equality (= or eq) and recursion, and this becomes a universal model of computation. 13 16 Homework Examples Evaluation Rules 1.Given a (list 6 2 3 8 9), find the minimum (there ● A number evaluates to itself. is already a min function available, but can you ● An atom evaluates to its current binding. implement yours?). Use operator <. – More about this later. 2.How to run my saved lisp program in prog.lisp ● A list is a computation without entering the interpreter? Use operator <. – Its first element must evaluate to an operation 3.Implement a binary search tree with insert, – The remaining elements are actual parameters remove and search operations. Use operator <. – The result is the application of the operation to the evaluated actuals. ButBut ifif eacheach listlist isis aa computation,computation, howhow dodo wewe distinguishdistinguish data?data? 14 17 Uniformity in Code and Data Quote ● Error if operator is undefined ● Expressions are atoms or lists – (1 2 3 4) ● Atoms are numeric or symbols => error ● Lists nest, to form trees ● Quote identifies data ● A program is a list. – (quote (1 2 3 4)) ((defundefun factfact (N)(N) => (1 2 3 4) (if (<= N 1) 1 (if (<= N 1) 1 – (quote (this is data and not a command)) (*(* (fact(-(fact(- NN 1))1)) N)N) )) => (THIS IS DATA AND NOT A COMMAND) )) – '(single quote also works) 15 => (SINGLE QUOTE ALSO WORKS) 18 List Decomposition Control Structures (defun(defun retfour()retfour() – (car '(this is a list of symbols)) ● Conditional (print(print “I“I amam inin four”)four”) => this atom – (if condition ifblock elseblock)44 )) – (cdr '(this is a list of symbols)) ● General ((defundefun ifelse(n)ifelse(n) => (is a list of symbols) list (cond(cond – (cond (if(if (=(= nn 0)0) (print(print “zero”))“zero”)) – (cdr '(this that)) (pred1 handler1) (if(if (=(= nn 3)3) (print(print “three”))“three”)) (if(if (=(= nn 1)1) (print(print “one”))“one”)) => (that) (pred2 handler2) (if(if (=(= nn (retfour))(retfour)) (print(print “four”))“four”)) – (cdr '(singleton)) ... (if(if (=(= nn 5)5) (print(print “five”))“five”)) ) )) => nil ; empty list )) – (car nil) (cdr nil) (ifelse(ifelse 5)5) 19 22 List Building Control Structures (defun(defun retfour()retfour() – (cons 'sahib '(biwi aur ghulam)) ● Conditional (print(print “I“I amam inin four”)four”) => (sahib biwi aur ghulam) 44 – (if condition ifblock elseblock) Error )) – (cons 'element-to-list ()) ● General ((defundefun ifelse(n)ifelse(n) => (element-to-list) (cond(cond – (cond (if(if (=(= nn 0)0) ((print((print “zero”)(print“zero”)(print – (cons 'a (cons 'b (cons 'c (cons 'd (cons 'e ()))))) (pred1 handler1) “after“after zero”)))zero”))) (if(if (=(= nn 3)3) (print(print “three”))“three”)) => (a b c d e) (pred2 handler2) (if(if (=(= nn 1)1) (print(print “one”))“one”)) – (list a b c d e) ... (if(if (=(= nn (retfour))(retfour)) (print(print “four”))“four”)) ) (if(if (=(= nn 5)5) (print(print “five”))“five”)) => error )) – (list 'a 'b 'c 'd 'e) )) (ifelse(ifelse 0)0) => (a b c d e) 20 23 Control Structures Control Structures (defun retfour() ● ● (defun retfour() Conditional Conditional (print(print “I“I amam inin four”)four”) – (if condition ifblock elseblock) – (if condition ifblock elseblock)44 )) ● General ● General ((defundefun ifelse(n)ifelse(n) ((defundefun ifelse(n)ifelse(n) (cond(cond (cond(cond – (cond – (cond (if(if (=(= nn 0)0) ((prognprogn (print(print “zero”)“zero”) (if(if (=(= nn 0)0) (print(print “zero”))“zero”)) (print(print “after“after zero”)))zero”))) (pred1 handler1) (if(if (=(= nn 3)3) (print(print “three”))“three”)) (pred1 handler1) (if(if (=(= nn 3)3) (print(print “three”))“three”)) (pred2 handler2) (if(if (=(= nn 1)1) (print(print “one”))“one”)) (pred2 handler2) (if(if (=(= nn 1)1) (print(print “one”))“one”)) (if(if (=(= nn 4)4) (print(print “four”))“four”)) ..

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    19 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us