77 Views

Download Presentation
##### Defining new functions (contd)

**An Image/Link below is provided (as is) to download presentation**

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -

**Defining new functions (contd)**xmemb[x, list] = ; is x a member of list? [ null?[list] NIL; | eq?[x, car[list]] T; | Txmemb[x, cdr[list]] ] Define a function that will return a count of how many times x appears in list A useful function: not[x] = ; returns negation; i.e., T if x is NIL and NIL if x is T [ eq[x, T] NIL; | T T; ] CSE 3341/655; Part 4**Function Definitions (contd.)**equal[ x, y ] = ; x and y may not be atoms [ atom[x] [atom[y] eq[x,y]; | T NIL; ] | atom[y] NIL; | equal[car[x], car[y]] equal[cdr[x], cdr[y]]; | T NIL; ] CSE 3341/655; Part 4**Defining new functions (contd)**xunion[s1, s2] = ; union of atomic lists, less duplicates [ null?[s1] s2 | null?[s2] s1 | T [ xmemb[car[s1],s2] xunion[cdr[s1], s2] | T cons[ car[s1], xunion[cdr[s1], s2] ] ] ] ; better: xunion[s1, s2] = [ null?[s1] s2 ; | null?[s2] s1 ; | xmemb[car[s1],s2] xunion[cdr[s1], s2] | T cons[ car[s1], xunion[cdr[s1], s2] ] ] CSE 3341/655; Part 4**Function Definitions (contd.)**addUpList[ L ] =; returns sum of all numbers in L [ null?[ L ] 0 | T +[ car[L], addUpList[ cdr[L] ] ] ] CSE 3341/655; Part 4**Function Definitions (contd.)**nNil[ n ] = ; returns a list with as many NILs as value of n [ =[ n, 0] NIL | T cons[ NIL, nNIL[ -[n, 1] ] ] ] number[x] : returns T if x is a numerical atom, NIL otherwise genEq[x,y] = ; works for both numbers and non-numeric atoms [ number[x] [number[y] =[x,y]; | T NIL; ]; | number[y] NIL; | T eq[x,y]; ] CSE 3341/655; Part 4**Different styles in Lisp**maxList[L] = ; returns max of number in non-empty list L ; Functional: [ null?[cdr[L]] car[L] | >[car[L], maxList[cdr[L]] car[L] | TmaxList[cdr[L]] ] ; Functional but better: [ null?[cdr[L]] car[L]; |T bigger[ car[L], maxList[cdr[L]]] ] ; define bigger ; imperative: maxList[L] = max2[car[L], cdr[L]] max2[x, L] :: [ null?[L] x | >[x, car[L]] max2[x, cdr[L]] | T max2[ car[L], cdr[L] ] ] CSE 3341/655; Part 4**More functions**• How do you obtain firstelement of a list? • How do you obtain the last element? [watch out!] • How do you append two lists? [No, not just cons!] • How do you reverse a list? [best: use imperative trick] CSE 3341/655; Part 4