Chapter 15
Chapter 15
Function
definition are written as a function name, followed by a list of parameters in parentheses, followed by the mapping expression.
Cube (x) = x * x * x ,x is real number Ex: cube(2.0) yields the value 8.0.
Lambda
Apply
to all
Construction
[f, g ]
Value 42 21 20 -1 6 12
DEFINE
Or
Output
Functions
Numeric
predicate functions
Return a Boolean value (true #t or false #f ()) =, <>, >, <, >=, <=, EVEN?, ODD?, ZERO?
Ex:
Factorial function f(n) = 1 if n=0 n* f(n-1) if n>0 Two way selector, If (only 1 predicate is true)
It has three parameters (predicate expr, then_expr, else_expr) Ex: (DEFINE (factorial n) (If (= n 0) 1 (* n (factorial (- n 1))) ))
(DEFINE
( compare x y) (COND ((> x y) (DISPLAY x is greater than y)) ((< x y) (DISPLAY y is greater than x)) (ELSE (DISPLAY x and y are equal)) )
QUOTE
There
CAR returns the first element of a given list. CDR returns the remainder of a given list after CAR is removed.
Examples
on CAR
(CAR (A B C)) returns A (CAR ((A B) C D)) returns (A B) (CAR A) is an error because A is not a list (CAR ()) is an error (CAR (A)) returns A
Examples
on CDR
(CDR (A B C)) returns (B C) (CDR ((A B) C D)) returns (C D) (CDR A) is an error because A is not a list (CDR (A)) returns () empty list
(DEFINE
(second (A B C))
returns B
CONS builds a list from its two arguments It inserts the first parameter as a new CAR of its second parameter Examples on CONS
(CONS A ()) returns (A) (CONS A (B C)) returns (A B C) (CONS () (A B)) returns (() A B) (CONS (A B) (C D)) returns ((A B) C D) (CONS A B) returns (A . B)
LIST
EQ?
takes two parameters, returns #t if both are the same, otherwise () Examples:
LIST?
NULL?
Member
LET
(LET(
yields 35
Same
1) Functional Composition
(CDR (CDR (A B C))) -> (CDR (B C)) returns (C) (CAR (CAR ((A B) B C))) -> (CAR (A B)) returns A (CDR (CAR ((A B C) D))) -> (CDR (A B C)) returns (B C) (NULL? (CAR (() B C))) -> (NULL? ()) returns #t (CONS (CAR (A B)) (CDR ( A B))) -> (CONS (A (B))) returns (A B)
2) An apply to all functional form mapcar has two parameters (function, list) It applies the given function to each element of the given list, and it returns a list of the results. Ex: (mapcar (LAMBDA (num) (* num num num)) (3 4 2 6)) Returns (27 64 8 216)
SET!